使用 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:~$
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP