While learning about forking and piping, I came across the following excellent tutorial: https://www.cs.rutgers.edu/~pxk/416/notes/c-tutorials/pipe.html
However, the tutorial goes into discussing how one can establish a pipe between 2 child processes that were spawned by the last parent. While it does a great job of that, a certain line of code has confounded me for a while:
while ((pid = wait(&status)) != -1) /* pick up all the dead children*/
fprintf(stderr, "process %d exits with %d\n", pid, WEXITSTATUS(status));
exit(0);
I am really confused about wait(&status)
(yes, I have read the man page at http://linux.die.net/man/2/wait). We just declare an int status
, never really give it a value, and just pass it to wait. Is this status set transparently in the wait()
function?
The man page says:
wait(): on success, returns the process ID of the terminated child; on error, -1 is returned.
So in the above lines of code, the while loop exits when wait(&status)
returns -1. This is jarring: was there an error, and why? How do we ensure that the parent keeps spinning until all its children terminate properly? What is 'status' anyway, and how is it set?
Edit: To add, the program does compile and run perfectly.