1

I use fork and execv to execute a child process. In the parent program, I have this:

int status;
wait(&status);
cout << "return code = " << status << endl;

Will that wait for the child process to terminate and then display it's return code?

node ninja
  • 31,796
  • 59
  • 166
  • 254
  • So far all the answers are wrong, since WEXITSTATUS has not even been mentioned. – node ninja Apr 27 '11 at 06:44
  • Note that the exit status is encoded as the high-order 8 bits of a 16-bit value, and the signal is encoded as the low-order 8 bits. If the process did not die of a signal, then the low-order bits are zero; if it did die of a signal, then the high-order bits are zero. See [`wait()` and `waitpid()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html) for the official POSIX definition; it doesn't mention sets of 8 bits, but provides macros to get at the status and signal information. – Jonathan Leffler Apr 27 '11 at 06:52

2 Answers2

1

You should use waitpid() if want to get status of specified child process. wait() will return status of first finished child process.

Community
  • 1
  • 1
Mihran Hovsepyan
  • 10,810
  • 14
  • 61
  • 111
  • 1
    If there's a single child, `wait()` works as well as `waitpid()`. In fact, even if there are multiple children, `wait()` works fine as long as you don't mind which 'corpse' you get first. If you use `waitpid()` to wait for a specific process that does not terminate, then the process might build up a collection of zombies - processes which are dead but for which the parent process has not yet waited. Also, be aware that you may have to tinker with SIGCHLD. – Jonathan Leffler Apr 27 '11 at 06:22
0

yes, it should from what i read http://linux.die.net/man/2/wait

Dan D.
  • 73,243
  • 15
  • 104
  • 123
  • 1
    `wait(&status)` is equivalent to `waitpid(-1, &status, 0)` which will wait for any child process. So as long as there is only one child process, the code will work as expected – mdec Apr 27 '11 at 06:09