fork()使用wait()从下到上执行进程

fork() 系统调用用于创建通常称为子进程的进程,创建它的进程称为父进程。现在,使用fork()创建的所有进程都同时运行。但是,如果我们希望创建的最后一个进程先执行,然后以这种方式从下到上执行,这样父进程最后执行,该怎么办呢。

null

这可以通过使用 等等 系统呼叫。然后,父进程可能会发出wait()系统调用,在子进程执行时暂停父进程的执行,当子进程完成执行时,它会将退出状态返回给操作系统。现在wait()挂起进程,直到其任何子进程完成执行。

图片[1]-fork()使用wait()从下到上执行进程-yiteyi-C++库

笔记 :这是一个linux系统调用,因此必须在linux或unix变体系统上执行。

// Program to demonstrate bottom to up execution
// of processes using fork() and wait()
#include <iostream>
#include <sys/wait.h> // for wait()
#include <unistd.h> // for fork()
int main()
{
// creating 4 process using 2 fork calls
// 1 parent : 2 child : 1 grand-child
pid_t id1 = fork();
pid_t id2 = fork();
// parent process
if (id1 > 0 && id2 > 0) {
wait(NULL);
wait(NULL);
cout << "Parent Terminated" << endl;
}
// 1st child
else if (id1 == 0 && id2 > 0) {
// sleep the process for 2 seconds
// to ensure 2nd child executes first
sleep(2);
wait(NULL);
cout << "1st child Terminated" << endl;
}
// second child
else if (id1 > 0 && id2 == 0) {
// sleep the process for 1 second
sleep(1);
cout << "2nd Child Terminated" << endl;
}
// grand child
else {
cout << "Grand Child Terminated" << endl;
}
return 0;
}


输出:

Grand Child Terminated
2nd Child Terminated
1st child Terminated
Parent Terminated
© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享