fork()使用C ++中的wait()从下到上执行进程
我们知道,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:~$