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 ... } ... }
We know if more than one child processes are terminated, then wait() reaps any arbitrarily child process but if we want to reap any specific child process, we use waitpid() function.
The system call wait() is easy. wait() takes the address of an integer variable and returns the process ID of the completed process. One of the main purposes of wait() is to wait for completion of child processes.
Orphan processes are an opposite situation to zombie processes, referring to the case in which a parent process terminates before its child processes, which are said to become "orphaned".
If parent process doesn't wait on the child process and the child process exits before the parent process then it becomes a "zombie" process. So, a wait() call is used to "reap" the process and release the system resources associated with the process.
pid_t child_pid, wpid; int status = 0; //Father code (before child processes start) for (int id=0; id<n; id++) { if ((child_pid = fork()) == 0) { //child code exit(0); } } while ((wpid = wait(&status)) > 0); // this way, the father waits for all the child processes //Father code (After all child processes end)
wait
waits for a child process to terminate, and returns that child process's pid
. On error (eg when there are no child processes), -1
is returned. So, basically, the code keeps waiting for child processes to finish, until the wait
ing errors out, and then you know they are all finished.
POSIX defines a function: wait(NULL);
. It's the shorthand for waitpid(-1, NULL, 0);
, which will suspends the execution of the calling process until any one child process exits. Here, 1st argument of waitpid
indicates wait for any child process to end.
In your case, have the parent call it from within your else
branch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With