I am trying to execute another program from within my own, but i don't understand a few things. So i wrote this code:
void run() {
cout << "##Run" << endl;
pid_t process_id = fork();
if (process_id == 0) {
char* args[] = { "sudo", "ls", "-l" };
auto i = execvp("sudo", args);
cout << "#Result: " << i << endl;
return;
} else if (process_id < 0) {
throw std::runtime_error("fork() failed");
} else if (process_id > 0) {
wait(&process_id);
}
return;
}
void run_decorator() {
cout << "###Run decorator: " << endl;
run();
}
int main() {
run();
run_decorator();
return 0;
}
And the output is
##Run
total 88
-rwxr-xr-x 1 bezik bezik 77560 Nov 29 19:53 colors
-rwxr-xr-x 1 bezik bezik 63 Nov 26 21:45 compile
drwxr-xr-x 2 bezik bezik 4096 Nov 26 20:46 headers
drwxr-xr-x 2 bezik bezik 4096 Nov 23 00:48 sources
###Run decorator:
##Run
#Result: -1
Can someone please explain to me, why execvp failed when called from run_decorator() function?