I'm hoping someone could shed some light on how to make the parent wait for ALL child processes to finish before continuing after the fork. I have cleanup code which I want to run but the child processes need to have returned before this can happen.
for (int id=0; id<n; id++) {
if (fork()==0) {
// Child
exit(0);
} else {
// Parent
...
}
...
}
POSIX defines a function:
wait(NULL);
. It's the shorthand forwaitpid(-1, NULL, 0);
, which will suspends the execution of the calling process until any one child process exits. Here, 1st argument ofwaitpid
indicates wait for any child process to end.In your case, have the parent call it from within your
else
branch.wait
waits for a child process to terminate, and returns that child process'spid
. On error (eg when there are no child processes),-1
is returned. So, basically, the code keeps waiting for child processes to finish, until thewait
ing errors out, and then you know they are all finished.Use waitpid() like this: