Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 wait()를 사용하여 아래에서 위로 프로세스를 실행하는 fork()

<시간/>

fork() 시스템 호출이 프로세스를 두 개의 프로세스로 나누는 데 사용된다는 것을 알고 있습니다. fork() 함수가 0을 반환하면 자식 프로세스이고 그렇지 않으면 부모 프로세스입니다.

이 예에서는 프로세스를 네 번 분할하고 상향식으로 사용하는 방법을 볼 것입니다. 따라서 처음에는 fork() 함수를 두 번 사용할 것입니다. 따라서 자식 프로세스를 생성한 다음 다음 포크에서 다른 자식을 생성합니다. 그 후 내부 포크에서 자동으로 손자를 생성합니다.

wait() 함수를 사용하여 약간의 지연을 생성하고 프로세스를 상향식으로 실행합니다.

예시 코드

#include <iostream>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;
int main() {
   pid_t id1 = fork(); //make 4 process using two consecutive fork. The main process, two children and one grand child
   pid_t id2 = fork();
   if (id1 > 0 && id2 > 0) { //when both ids are non zero, then it is parent process
      wait(NULL);
      wait(NULL);
      cout << "Ending of parent process" << endl;
   }else if (id1 == 0 && id2 > 0) { //When first id is 0, then it is first child
      sleep(2); //wait 2 seconds to execute second child first
      wait(NULL);
      cout << "Ending of First Child" << endl;
   }else if (id1 > 0 && id2 == 0) { //When second id is 0, then it is second child
      sleep(1); //wait 2 seconds
      cout << "Ending of Second child process" << endl;
   }else {
      cout << "Ending of grand child" << endl;
   }
   return 0;
}

출력

soumyadeep@soumyadeep-VirtualBox:~$ ./a.out
Ending of grand child
Ending of Second child process
Ending of First Child
Ending of parent process
soumyadeep@soumyadeep-VirtualBox:~$