programing

부모가 모든 자식 프로세스가 완료될 때까지 대기하도록 하려면 어떻게 해야 합니까?

kingscode 2022. 7. 11. 23:40
반응형

부모가 모든 자식 프로세스가 완료될 때까지 대기하도록 하려면 어떻게 해야 합니까?

어떻게 하면 부모가 모든 자녀 과정이 끝날 까지 기다린 후에 포크를 계속 사용할 수 있는지 누군가가 밝혀주셨으면 합니다.실행하려는 정리 코드가 있지만 하위 프로세스가 반환된 후에 이 작업을 수행할 수 있습니다.

for (int id=0; id<n; id++) {
  if (fork()==0) {
    // Child
    exit(0);      
  } else {
    // Parent
    ...
  }
  ...
}
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 하위 프로세스가 종료되기를 기다린 후 해당 하위 프로세스의 데이터를 반환합니다.pid에러(예를 들면, 자프로세스가 없는 경우),-1이 반환됩니다.따라서 기본적으로 코드는 하위 프로세스가 완료될 때까지 계속 대기합니다.wait에러를 검출하면, 에러가 모두 종료됩니다.

POSIX는 함수를 정의합니다.wait(NULL);의 줄임말입니다.waitpid(-1, NULL, 0);1개의 자 프로세스가 종료될 때까지 콜프로세스의 실행을 정지합니다.여기 첫 번째 인수waitpid자녀 프로세스가 종료될 때까지 대기함을 나타냅니다.

당신의 경우, 부모에게 자신의 내부에서 전화를 걸도록 합니다.else분점.

사용방법:

while(wait(NULL) > 0);

이렇게 하면 모든 하위 프로세스를 대기하고 모든 하위 프로세스가 반환된 경우에만 다음 지시로 이동합니다.

다음과 같이 waitpid()를 사용합니다.

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!.");    
    }
}

언급URL : https://stackoverflow.com/questions/19461744/how-to-make-parent-wait-for-all-child-processes-to-finish

반응형