Search code examples
cprocesshandlerwaitpidsigchld

C - Under what conditions will a call to waitpid() return -1, signalling an error?


I'm writing a SIGCHLD handler and I'm wondering under what conditions would a call to waitpid() return -1?

More specifically, if I create a loop in which I call waitpid(...) and want it to run until all terminated child processes have been reaped, would I be iterating until waitpid(...) returns -1? Otherwise, how can I know if there are any more children that require reaping?


Solution

  • waitpid() can return -1 under these circumstances:

    1. The process has no children that it has not yet waited for. errno is set to ECHILD in this case. If you're looping to reap all children or all children in your process group (i.e. you set pid to -1 or 0), you should break out of the loop when this happens. This can also happen if the signal action for SIGCHLD is set to SIG_IGN or the SA_NOCLDWAIT flag is set for the signal.
    2. A problem was detected in the arguments. If the problem is with the options argument, errno will be set to EINVAL. If the pid is greater than 0 (so you're waiting for a specific child) and doesn't exist or is not a child of this process, errno will be set to ECHILD; this is probably not applicable if you're in a wait loop. These generally indicate a problem in your code, you should probably report it or log it, and exit.
    3. The call was interrupted by a signal. errno will be set to EINTR. You should probably stay in the loop when this happens.