2

I know that one of the differences between wait() and waitpid() is that waitpid having a WNOHANG option which tells the waitpid not to block if there are running children that have not yet terminated. Such as:

while (  (pid = waitpid(-1, &stat, WNOHANG)) > 0)
    printf("Child %d terminated\n", pid);

If I use wait() instead of waitpid(), there is no way to prevent wait() from blocking if there are running children that have not yet terminated. However, I wonder if wait() works fine here, even though it may block.

Nmzzz
  • 2,462
  • 3
  • 19
  • 18
  • 2
    That loop will only loop as long as there are processed being terminated. Otherwise if no child processes have terminated, it will only cause one call to `waitpid`, which returns `0` and breaks out of the loop. – Some programmer dude Feb 04 '13 at 08:18
  • If I put this code into a signal handler(catching the SIGCHLD signal), which excutes because there is a child have terminated, will wait() works fine? – Nmzzz Feb 04 '13 at 08:25
  • If you received a `SIGCHLD` signal, you _know_ something happened with a child process, and therefore can call `wait` without it blocking. – Some programmer dude Feb 04 '13 at 08:28
  • If there are many children processes, some have terminated but some have not, can I use such a wait() handler? – Nmzzz Feb 04 '13 at 08:31
  • Then you should use the loop you have in your question. – Some programmer dude Feb 04 '13 at 08:35
  • 4
    Never use `wait()`; it's an obsolete API with several problems. If there are two places in your code where you create children, `wait()` can reap the wrong pid (this is a bug for example in old implementations of `system()`). There's rarely any reason not to `waitpid()` for the process you're actually interested in and keep things clean. – Nicholas Wilson Feb 04 '13 at 08:35

1 Answers1

-2

we cannot call wait in a loop, because there is no way to prevent wait from blocking if there are running children that have not yet terminated.

yamorn
  • 7
  • 2