I have a function in C that creates a child process and uses execvp() to execute a certain task.
pid_t pid = fork();
if (pid == 0) {
if (execvp(cmd->arg_array[0], cmd->arg_array) == -1) {
exit(-1);
return ERROR;
}
} else if (pid < 0)
return ERROR;
//Some more code...
return NO_ERROR;
As you can see, if the task fails, the process containing it should be deleted and the function returned with ERROR value.
I tried implementing this functionality with an exit(-1) (and _exit() also), but the return statement is never reached, since the code is in the parent process zone. Also, if I remove the exit() and let the function return the error, the process keeps existing and interferes with the program functioning. How can I kill the created child process before the function returns when execvp task fails?
No, that's not what happens. A successful
fork()creates a new process and returns0to this new process. In you example,execvpis executed in this new process and if it fails, you immediately doexit(-1);, at which point the process terminates and the linereturn ERROR;will never be reached.You can collect the child's exit status in the parent process by using
waitorwaitpid. UseWIFEXITED/WEXITSTATUS,WIFSIGNALED/WTERMSIG,WIFSTOPPED/WSTOPSIGandWIFCONTINUEDto unpack the information about how it exited (or stopped/continued).Example:
Note: The function
_exit()is likeexit(), but does not call any functions registered withatexit()oron_exit()and you probably wouldn't want those to be called just becauseexecvpfailed.When a child process is created via
fork(), it inherits copies of its parent'son_exitregistrations. Upon a successful call to one of theexec()functions (likeexecvp), all registrations are removed.