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

后端 未结 3 1041
有刺的猬
有刺的猬 2020-11-27 02:47

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 whi

相关标签:
3条回答
  • 2020-11-27 03:20

    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!.");    
        }
    }
    
    0 讨论(0)
  • 2020-11-27 03:21
    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.

    0 讨论(0)
  • 2020-11-27 03:27

    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.

    0 讨论(0)
提交回复
热议问题