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

后端 未结 3 1085
有刺的猬
有刺的猬 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!.");    
        }
    }
    

提交回复
热议问题