Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit a child process and return its status from execvp()?

Tags:

c

fork

exit

exec

In my simple custom shell I'm reading commands from the standard input and execute them with execvp(). Before this, I create a fork of the current process and I call the execvp() in that child process, right after that, I call exit(0).

Something like this:

pid = fork();

if(pid == -1) {
    perror("fork");
    exit(1);
}

if(pid == 0) {
    // CHILD PROCESS CODE GOES HERE...
    execvp(pArgs[0], pArgs);
    exit(0);
} else {
    // PARENT PROCESS CODE GOES HERE...
}

Now, the commands run with execvp() can return errors right? I want to handle that properly and right now, I'm always calling exit(0), which will mean the child process will always have an "OK" state.

How can I return the proper status from the execvp() call and put it in the exit() call? Should I just get the int value that execvp() returns and pass it as an exit() argument instead of 0. Is that enough and correct?

like image 239
rfgamaral Avatar asked May 24 '09 14:05

rfgamaral


People also ask

How do I exit Execvp?

And if the execvp() does fail, you should have exit(1) or exit(EXIT_FAILURE) or anything other than exit(0) - to indicate the failure. Side note: you probably want _Exit() instead of exit() .

How do you exit a child process in C++?

execvp will exit the child if successfull so you don't have to exit. On execve failure I simply use exit(EXIT_FAILURE); in the child. So it's looks like it's better to use _exit() in a fork child specially when you are in C++ :p.

What does Execvp return?

execvp() returns a negative value if the execution fails (e.g., the request file does not exist).

How do I print exit status of child process?

You can get the exit status of the child via the first argument of wait() , or the second argument of waitpid() , and then using the macros WIFEXITED and WEXITSTATUS with it. waitpid() will block until the process with the supplied process ID exits.


1 Answers

You need to use waitpid(3) or wait(1) in the parent code to wait for the child to exit and get the error message.

The syntax is:

pid_t waitpid(pid_t pid, int *status, int options);

or

pid_t wait(int *status);

status contains the exit status. Look at the man pages to see you how to parse it.


Note that you can't do this from the child process. Once you call execvp the child process dies (for all practical purposes) and is replaced by the exec'd process. The only way you can reach exit(0) there is if execvp itself fails, but then the failure isn't because the new program ended. It's because it never ran to begin with.

Edit: the child process doesn't really die. The PID and environment remain unchanged, but the entire code and data are replaced with the exec'd process. You can count on not returning to the original child process, unless exec fails.

like image 136
Nathan Fellman Avatar answered Sep 30 '22 18:09

Nathan Fellman