题目
请利用 fork() 函数创建 8 个进程,这些进程具有以下关系,最后在每个进程中打印自己的 PID 作为输出结果。
点拨
注意:
在条件语句的动作范围内,除非立刻运行到 main() 的返回语句,否则,需要
return 0;
来让执行完毕的父进程代码或子进程代码立刻结束。
父进程会创建多个子进程,但是在不出错的情形下,每次 fork() 的返回值都会大于 0。这时候任选一个大于 0 的返回值,并根据返回值来执行父进程的动作,避免重复执行。在其中一个子进程创建出错时,可以在报告错误后不立即返回,而是报告下一个成功创建的子进程的 PID。
源代码
#include <iostream>
#include <unistd.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
pid_t pid[3];
pid[0] = fork();
if (pid[0] > 0) cout << "PID of the parent process: " << getpid() << endl;
else if (pid[0] == 0) {
{
pid_t pid[2];
pid[0] = fork();
if (pid[0] > 0) cout << "PID of the 1st child process: " << getpid() << endl;
else if (pid[0] == 0) {
{
pid_t pid = fork();
if (pid > 0) cout << "PID of the 1st grandchild process: " << getpid() << endl;
else if (pid == 0) cout << "PID of the 1st great-grandchild process: " << getpid() << endl;
else cout << "Great-grandchild 1: Fork Error." << endl;
}
return 0;
}
else cout << "Grandchild 1: Fork Error." << endl;
pid[1] = fork();
if (pid[1] > 0) ;
else if (pid[1] == 0) cout << "PID of the 2nd grandchild process: " << getpid() << endl;
else cout << "Grandchild 2: Fork Error." << endl;
}
return 0;
}
else cout << "Child 1: Fork Error." << endl;
pid[1] = fork();
if (pid[1] > 0) ;
else if (pid[1] == 0) {
{
pid_t pid = fork();
if (pid > 0) cout << "PID of the 2nd child process: " << getpid() << endl;
else if (pid == 0) cout << "PID of the 2nd grandchild process: " << getpid() << endl;
else cout << "Grandchild 3: Fork Error." << endl;
}
return 0;
}
else cout << "Child 2: Fork Error." << endl;
pid[2] = fork();
if (pid[2] > 0) ;
else if (pid[2] == 0) cout << "PID of the 3rd child process: " << getpid() << endl;
else cout << "Child 3: Fork Error." << endl;
return 0;
}