【发布时间】:2015-09-30 00:38:19
【问题描述】:
您好,我有一个关于使用 fork() 创建更多子代的问题,这是基于我之前提出的 using fork() to make 3 children out of 1 parent in C (not C++) 的一个问题
我希望我的输出看起来像这样(#s 被简化并仅用于说明顺序)
[grandpa]hi am I PID 1234 and I come from ####(dont care what this number is)
[dad] hi i am PID 2111 and I come from PPID 1234
[son] hi i am PID 3111 and I come from PPID 2111
[son] hi i am PID 3112 and I come from PPID 2111
[son] hi i am PID 3113 and I come from PPID 2111
[dad] hi i am PID 2112 and I come from PPID 1234
[son] hi i am PID 3111 and I come from PPID 2112
[son] hi i am PID 3112 and I come from PPID 2112
[son] hi i am PID 3113 and I come from PPID 2112
[dad] hi i am PID 2113 and I come from PPID 1234
[son] hi i am PID 3111 and I come from PPID 2113
[son] hi i am PID 3112 and I come from PPID 2113
[son] hi i am PID 3113 and I come from PPID 2113
但我的输出如下所示:
除了最后一个之外,关于爸爸 ppid,最后似乎还可以,而且大多数 PID 似乎都乱序了。我不知道为什么有一个儿子,然后是五个,然后是三个儿子。这是我的代码:
int grandforking(null)
{
Gen1 (null);
return 0;
}
int Gen1 (null)
{
void about(char *);
int i=0;
int j=0;
about("grandpa");
for(i = 0; i < 3; i++ )
{
pid_t child = 0;
child = fork();
if (child < 0)
{ //unable to fork error
perror ("Unable to fork");
exit(-1);
}
else if (child == 0)
{ //child process
Gen2 (null);
exit(0);
}
else
{ //parent process
//(do nothing)
}
}
for(j = 0; j < 3; j++ )
{
wait(NULL);//wait for parent to acknowledge child process
}
return 0;
}
int Gen2 (null)
{
int i=0;
int j=0;
about("dad");
for(i = 0; i < 3; i++ )
{
pid_t child = 0;
child = fork();
if (child < 0)
{ //unable to fork error
perror ("Unable to fork");
exit(-1);
}
else if (child == 0)
{ //child process
about ("son");
exit(0);
}
else
{ //parent process
//(do nothing)
}
}
for(j = 0; j < 3; j++ )
{
wait(NULL);//wait for parent to acknowledge child process
}
return 0;
}
【问题讨论】:
-
啊,我只是想对我的标题有所帮助,因为有时我在输入 C 时会被问到是否是 C++
-
代码运行正常。您有三个从 5841 产生的父亲,三个来自 5842 的儿子,三个来自 5843 的儿子和三个来自 5850 的儿子。叔侄之间 printfs 的顺序不是代码试图控制的东西。该代码仅保证父亲在其任何儿子之前打印。
-
我发现所有多余的单词和英语都使调试和查看发生了什么变得更加困难。我只是列出
<pid> (parent: <pid>)并根据需要缩进以指示父/子关系并显示流程树。 -
好的,谢谢大家。如果有人对如何更好地格式化输出有任何想法(有点像 Arlie 所说的),我想我现在就让它保持原样。