When and why should you use WNOHANG with waitpid()?

user3305321 picture user3305321 · Mar 3, 2015 · Viewed 7.6k times · Source

I'm currently in a systems programming class and we went over the wait system call functions today. I was reading over the section on waitpid() system call and in the options section it lists one called WNOHANG.

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

WNOHANG: If no child specified by pid (from the parameters) has yet changed state, then return immediately, instead of blocking. In this case, the return value of waitpid() is 0. If the calling process has no children that match the specification in pid, waitpid() fails with the error ECHILD.

I understand waitpid() was implemented to solve the limitations in wait(); however, I'm not really sure about why you would use the WNOHANG option flag.

If I were to render a guess it would be so that the parent process can preform other tasks and perhaps keep checking on its children to see if any of them have terminated. Sort of how a demon process sits in the background and waits for requests.

Any situational examples or regular examples would help as well.

Thanks in advance!

Answer

Tomasz Myrta picture Tomasz Myrta · Mar 3, 2015

You don't need to keep checking on children. It is job of SIGCHLD signal handler. Every time this handler is fired, you check terminated children:

pid_t pid;
int status;
while ((pid=waitpid(-1,&status,WNOHANG)) > 0)
{
  //process terminated child
}