我不知道如何解决这个问题。我需要在 C 中使用 fork()
、if
和 else
创建一个进程树。
这棵树需要看起来像这样:
a.out---a.out---a.out
|
|--a.out---a.out---a.out
|
|--a.out---a.out---a.out
|
|--a.out
我已经有了这个:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main (void){
if(fork()){
if(fork()){}
else{}
if(fork()){}
else{fork();}
}
else{}
pause();
return 0;
}
这将创建一个如下所示的进程树:
a.out---a.out
|
|--a.out---a.out---a.out
|
|--a.out---a.out
最佳答案
这看起来应该可以做到:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
if (fork()) {
// parent
if (fork()) {
// parent
if (fork()) {
// parent
if (fork()) {
// parent
}
else {
// child 4
}
}
else {
// child 3
if (fork()) {
// child 3
}
else {
// child 1 of child 3
if (fork()) {
// child 1 of child 3
}
else {
// grandchild 1 of child 3
}
}
}
}
else {
// child 2
if (fork()) {
// child 2
}
else {
// child 1 of child 2
if (fork()) {
// child 1 of child 2
}
else {
// grandchild 1 of child 2
}
}
}
}
else {
// child 1
if (fork()) {
// child 1
}
else {
// child 1 of child 1
}
}
pause();
return 0;
}
理想情况下,您可以添加一些存储各种 PID 的变量,并将它们与它们的父级一起打印出来,以便您可以看到它。
关于在C中使用fork()创建特定的进程树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24071471/