为什么这个fork()输出会产生8而不是5? [英] why does this fork() out put produce 8 instead of 5?

查看:95
本文介绍了为什么这个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().

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

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆