Warm tip: This article is reproduced from stackoverflow.com, please click
c pthreads fork child-process pid

How to check if all child processes ended?

发布于 2020-03-27 15:45:15

I am trying to create an assignment where I want to check if all child process created by students have exited. As I am not calling fork, I don't have access to thread ids. Is there a way to check if the current process doesn't have any children without knowing thread ids of child processes created?

I checked many questions but every solution consists of the use of return value from the fork call. Any help is appreciated.

Thank you.

Questioner
Mandar Sadye
Viewed
16
Ctx 2020-01-31 17:20

You can call

int st = waitpid(-1, NULL, WNOHANG);

The first argument tells waitpid() to wait for any child process to exit, not for a specific pid.

The third argument is a flag, that makes waitpid() return immediately instead of blocking.

Now there are three possible outcomes:

  • return value is -1 and errno is ECHILD: this means, that there is no child process present at all
  • return value is >0: this denotes, that a child has exited in the past, but the return value was not yet collected (a so-called zombie process). Now iterate the process (call waitpid() again).
  • return value is 0: in this case, there are child processes available that are still running.

This should cover all cases you ask for.