不完全了解开关程序输出的叉子
我一直在尝试了解该程序的输出,但我仍然不明白。
main()
{
int pid, i;
pid = getpid();
for (i = 0; i < 25; i++)
{
switch (fork())
{
case 0:
if (pid % 2 == 0)
{
exit(0);
break;
}
default:
if (pid % 2 != 0)
{
exit(0);
}
}
}
printf("I am the process %d and my father is the process %d\n", getpid(), getppid());
while (wait(NULL) > 0) {}
return 0;
}
当我运行此功能时,它会返回:
我是过程11110,父亲是过程26453
但是,如果您要运行上述代码而没有两个“%2”,它将不会返回任何内容。
我对此感到非常困惑。我以为它会工作的方式(对于没有“%2”的代码)是,对于每个迭代:
- 孩子(pid == 0)将完成其过程(杀死子过程),并且始终从开关中脱离(不是影响for循环)
- 父亲/主过程将等到孩子死去
- 接下来的迭代
是正确的吗?如果是这样,“%2”会怎样?
I have been trying to understand the output of this program, but still I don’t quite get it.
main()
{
int pid, i;
pid = getpid();
for (i = 0; i < 25; i++)
{
switch (fork())
{
case 0:
if (pid % 2 == 0)
{
exit(0);
break;
}
default:
if (pid % 2 != 0)
{
exit(0);
}
}
}
printf("I am the process %d and my father is the process %d\n", getpid(), getppid());
while (wait(NULL) > 0) {}
return 0;
}
When I run this, it returns:
I am the process 11110 and my father is the process 26453
However, if you were to run the above code without both "% 2", it won't return anything.
I am very confused about this. The way I thought it would work (for the code without "% 2") is, for each for iteration:
- the child (pid==0) would finish its process (killing the child process) and always break from the switch (not affecting the for loop)
- the father/main process will wait until the child dies
- next for iteration
Is the above approach correct? If so, how would it be with "% 2"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有
%2
您要获得的:因为
pid
不是0,父母将在第一个fork之后立即
,因此您不会看到打印语句。退出(0)
()Without
% 2
you'd get:Since
pid
is not 0, the parent wouldexit(0)
immediately after the firstfork()
, so you won't see a print statement.