[c] 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
    ...
  }
  ...
}

This question is related to c process operating-system fork posix

The answer is


Use waitpid() like this:

pid_t childPid;  // the child process that the execution will soon run inside of. 
childPid = fork();

if(childPid == 0)  // fork succeeded 
{   
   // Do something   
   exit(0); 
}

else if(childPid < 0)  // fork failed 
{    
   // log the error
}

else  // Main (parent) process after fork succeeds 
{    
    int returnStatus;    
    waitpid(childPid, &returnStatus, 0);  // Parent process waits here for child to terminate.

    if (returnStatus == 0)  // Verify child process terminated without error.  
    {
       printf("The child process terminated normally.");    
    }

    if (returnStatus == 1)      
    {
       printf("The child process terminated with an error!.");    
    }
}

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.


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.


Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to process

Fork() function in C How to kill a nodejs process in Linux? Xcode process launch failed: Security Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes Linux Script to check if process is running and act on the result CreateProcess error=2, The system cannot find the file specified How to make parent wait for all child processes to finish? How to use [DllImport("")] in C#? Visual Studio "Could not copy" .... during build How to terminate process from Python using pid?

Examples related to operating-system

Context.startForegroundService() did not then call Service.startForeground() Fork() function in C python: get directory two levels up Find Process Name by its Process ID Best way to find os name and version in Unix/Linux platform How to run a program without an operating system? How to make parent wait for all child processes to finish? Get operating system info Running windows shell commands with python What are the differences between virtual memory and physical memory?

Examples related to fork

How to use execvp() Example of waitpid() in use? How to make parent wait for all child processes to finish? fork: retry: Resource temporarily unavailable fork() child and parent processes How to kill a child process by the parent process? How to use shared memory with Linux in C The difference between fork(), vfork(), exec() and clone() fork() and wait() with two child processes Redirecting exec output to a buffer or file

Examples related to posix

How to make parent wait for all child processes to finish? Kill all processes for a given user What is the proper #include for the function 'sleep()'? What is /dev/null 2>&1? How to kill all processes with a given partial name? What can lead to "IOError: [Errno 9] Bad file descriptor" during os.system()? How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`? Converting year and month ("yyyy-mm" format) to a date? CRON job to run on the last day of the month Checking if a file is a directory or just a file