Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

fork() เพื่อดำเนินการกระบวนการจากล่างขึ้นบนโดยใช้ wait() ใน C++


เรารู้ว่าการเรียกระบบ 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:~$