使用 wait() 從底到頂執行 C++ 程序的 fork() 函式
我們知道 fork() 系統呼叫用於將程序分成兩個程序。如果函式 fork() 返回 0,則它是子程序,否則它是父程序。
在本示例中,我們將看到如何將程序分成四次,並以自下而上方式使用它們。因此,首先我們將使用兩次 fork() 函式。因此,它將生成一個子程序,然後從下一個 fork 中它將生成另一個子程序。之後,從內部 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:~$
廣告