【发布时间】:2018-08-21 22:58:01
【问题描述】:
所以我想编写一个程序来创建多级子进程。单亲和独生子女。
示例:父->child1->child2->child3。像那样。 See image here
但问题是我想从终端获取输入,将创建多少子进程(单父 - 单子进程)。
那么我怎样才能将 嵌套 if 语句修改为某个循环,以便它可以创建我想要的子进程。
这是我的代码
#include<stdio.h>
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main() {
int a, b;
{
if(fork() == 0)
{
printf("child my pid is %d ppid is %d\n",getpid(),getppid());
if(fork()== 0)
{
printf("child my pid is %d ppid is %d\n",getpid(),getppid());
if(fork()== 0)
{
printf("child my pid is %d ppid is %d\n",getpid(),getppid());
}
}
}
else
printf("father my pid is %d ppid is %d\n",getpid(),getppid());
}
for(int i=0;i<3;i++)
wait(NULL);
return 0;
}
输出到这里:
father my pid is 4496 ppid is 3621
child my pid is 4497 ppid is 4496
child my pid is 4498 ppid is 4497
child my pid is 4499 ppid is 4498
谢谢,终于成功了。
【问题讨论】: