Unix:我如何使用fork来制作一些在层次结构中看起来像这样的进程



我正在创建一个.c文件,然后使用gcc进行编译。我想使用fork,以便创建以下7个进程,并显示层次结构。我该怎么做?另外,我必须使用wait来进行吗

A
/      
B         C
|
D
/  |  
E    F   G

我在另一个网站上发现有人有类似的问题,我已经更新了他的解决方案以适应我的情况。这可能是一个解决方案:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main() {
int status = 0;
printf("I am: %dnn", (int)getpid());
pid_t pid = fork(); // fork a child
if(pid == 0)
{
printf("Hi I'm process %d and my parent is %dn",getpid(),getppid());
exit(1);
}
else
{
pid_t childPid = wait(&status);
pid_t pid = fork(); // fork a child
if (pid == 0)
{
printf("Hi I'm process %d and my parent is %d.n", getpid(), getppid());
pid = fork(); // fork a child
if (pid == 0)
{
printf("Hi I'm process %d and my parent is %d.n",getpid(),getppid());
pid = fork();
if(pid == 0)
{
printf("Hi I m process %d and my parent is %dn", getpid(), getppid());
exit(4);
}
else
{
pid = fork();
if(pid==0)
{
printf("Hi i m process %d and my parent is %dn", getpid(), getppid());
exit(5);
}
else
{
pid = fork();
if(pid == 0)
{
printf("Hi i m process %d and my parent is %dn", getpid(), getppid());
exit(6);
}
}
}
exit(3);
}
exit(2);
}
}
return 0;
}

相关内容

最新更新