帮助了解此 C 代码使用 fork() 生成的输出
我正在尝试使用 fork() 找出 C 代码块的输出,但在理解为什么它会这样出现时遇到一些问题。据我所知,当使用 fork() 时,它会并行启动程序的另一个实例,并且子实例将返回 0。有人可以逐步解释下面代码块的输出吗?谢谢。 编辑:我忘记在 for 循环之后添加 exit(1)。我的歉意。
main() { int status, i;
for (i=0; i<2; ++i){
printf("At the top of pass %d\n", i);
if (fork() == 0){
printf("this is a child, i=%d\n", i);
} else {
wait(&status);
printf("This is a parent, i=%d\n", i);
}
}
exit(1);
}
I am trying to figure out the output for a block of C code using fork() and I am having some problems understanding why it comes out the way it does. I understand that when using fork() it starts another instance of the program in parallel and that the child instance will return 0. Could someone explain step by step the output to the block of code below? Thank you. EDIT: I FORGOT TO ADD THE EXIT(1) AFTER THE FOR LOOP. MY APOLOGIES.
main() { int status, i;
for (i=0; i<2; ++i){
printf("At the top of pass %d\n", i);
if (fork() == 0){
printf("this is a child, i=%d\n", i);
} else {
wait(&status);
printf("This is a parent, i=%d\n", i);
}
}
exit(1);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个循环中发生的情况是第一个进程分叉。在其中一个中,
fork()
返回 0,在另一个中,它返回子进程的 pid 因此,您将得到一个打印出“这是一个子进程”的结果,另一个打印出“这是一个子进程”的结果。一位家长”。这两个过程都继续循环,将i
增加到 1,然后再次fork()
。现在您有四个进程:两个子进程和两个父进程。所有四个进程都会将i
增加到 2 并跳出循环。如果将循环终止条件增加到
i<3
,那么下一次循环时,所有四个进程都将执行fork()
,总共有八个进程。如果循环中没有限制,你就会有一个 fork 炸弹,你可以在其中只是在每个循环中以指数方式创建越来越多的进程,直到系统耗尽资源。What happens on the first loop is that the first process forks. In one,
fork()
returns 0 and in the other it returns the pid of the child process So you'll get one that prints out "this is a child" and one that prints out "this is a parent". Both of those processes continue through the loop, incremementi
to 1 andfork()
again. Now you've got four processes: two children and two parents. All four processes will incrementi
to 2 and break out of the loop.If you increased the loop termination condition to
i<3
then the next time around the loop all four processes will executefork()
and you'd have eight processes in total. If there was no limit in the loop, you'd have a fork bomb where you'd just exponentially create more and more processes each loop until the system runs out of resources.这段代码可能很难解释。原因是第一个子进程不会退出,并且会自行调用 fork。尝试修改代码以在每个打印行上包含进程 ID,例如:
然后注意子进程如何成为父进程...
This code can be tricky to explain. The reason why is that the first child does not exit and will itself call fork. Try modifying the code to include the process id on each print line such as:
Then notice how the child becomes the parent...