Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make parent wait for all child processes to finish?

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     ...   }   ... } 
like image 982
Donatello Avatar asked Oct 19 '13 02:10

Donatello


People also ask

Does wait () wait for all child processes?

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.

Which function is used for waiting for a child process to complete?

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.

Can parent process finish before child?

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".

Why wait function is important for a parent?

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.


2 Answers

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 waiting errors out, and then you know they are all finished.

like image 50
adrisons Avatar answered Sep 28 '22 05:09

adrisons


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.

like image 33
xxx7xxxx Avatar answered Sep 28 '22 03:09

xxx7xxxx