为什么这个fork()输出会产生8而不是5?

编程入门 行业动态 更新时间:2024-10-12 16:22:20
本文介绍了为什么这个fork()输出会产生8而不是5?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以我必须找到使用fork()方法的此代码的输出.我以为输出是5个"hello",但是却得到了8个.为什么?这是代码:

So I have to find the output of this code which is using the fork() method. I thought the output was 5 "hello" s but instead I got 8. Why is that? This is the code:

#include "csapp.h" void doit() { Fork(); Fork(); printf("hello\n"); return; } int main() { doit(); printf("hello\n"); exit(0); }

推荐答案

以下是您的代码正在做的事情:

Here's what your code is doing:

main->doit()->Fork()->Fork()->printf()->return->printf()->exit() | | | ----->printf()->return->printf()->exit() | ----->Fork()->printf()->return->printf()->exit() | ----->printf()->return->printf()->exit()

如您所见,您总共有8个呼叫printf().

As you can see, you have a total of 8 calls to printf().

如果您选择在main和doit函数中打印不同的字符串,这将使您更容易了解发生了什么.

It would have been easier for you to see what was going on if you chose to print different strings in your main and doit functions.

在每个printf()调用上设置断点是解决此类问题的另一种有效策略.

Setting breakpoint on each printf() call is another effective strategy for figuring out these kinds of problems.

更多推荐

为什么这个fork()输出会产生8而不是5?

本文发布于:2023-10-09 05:36:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474852.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不是   fork

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!