Search code examples
linuxunixwaitpid

waitpid - difference between first parameter pid=-1 and pid=0


I am reading http://www.tutorialspoint.com/unix_system_calls/waitpid.htm regarding the waitpid function. It says this about the first parameter, pid,

 -1  meaning wait for any child process.  
 0  meaning wait for any child process whose process group ID is equal to that of the calling process.  

May I know what does "any child process" mean, any child process of whom? What sort of situation would one need to use a value of -1?


Solution

  • By “any child process”, it means any process that is a child of the process that called waitpid.

    You would use a pid argument of -1 if you want to wait for any of your children. The most common use is probably when you have multiple children and you know at least one has exited because you received SIGCHLD. You want to call waitpid for each child that has exited, but you don't know exactly which ones have exited. So you loop like this:

    while (1) {
        int status;
        pid_t childPid = waitpid(-1, &status, WNOHANG);
        if (childPid <= 0) {
            break;
        }
    
        // Do whatever you want knowing that the child with pid childPid
        // exited. Use status to figure out why it exited.
    }