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.
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:
-1
and errno
is ECHILD
: this means, that there is no child process present at all>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).0
: in this case, there are child processes available that are still running.This should cover all cases you ask for.
AFAICT, the students can create processes that will not be waited for with this approach, by simply
fork()
ing in their process.@EOF The main question was:_Is there a way to check if the current process doesn't have any children without knowing thread ids of child processes created?_, which is extensively answered here, I think
But if you actually read the question it's clear that this won't work for the stated problem.
@EOF No, I think that you misunderstand the OP
Maybe, but to quote: "As I am not calling fork [...]" implies that the students are calling
fork()
. It seems difficult to imagine a situation where the students are callingfork()
, but cannot callfork()
in the child. If the stated goal of the question is to "check if all child process created by students have exited", then only a very narrow understanding of the question would make this a good answer.