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

Ada*_*ker -2 c linux fork

所以我必须找到使用该fork()方法的代码的输出.我认为输出是5"你好",但我得到8.为什么?这是代码:

#include "csapp.h"

void doit()
{
    Fork();
    Fork();
    printf("hello\n");
    return;
}

int main()
{
    doit();
    printf("hello\n");
    exit(0);
}
Run Code Online (Sandbox Code Playgroud)

Cal*_*leb 6

这是您的代码正在做的事情:

main->doit()->Fork()->Fork()->printf()->return->printf()->exit()
                |       |
                |       ----->printf()->return->printf()->exit()
                |
                ----->Fork()->printf()->return->printf()->exit()
                        |
                        ----->printf()->return->printf()->exit()
Run Code Online (Sandbox Code Playgroud)

如您所见,您总共有8个电话printf().

如果你选择在你的maindoit函数中打印不同的字符串,那么你会更容易看到发生了什么.

在每次printf()通话中设置断点是解决这些问题的另一种有效策略.


Rik*_*son 5

首先你调用fork,你的一个进程分成两个.然后你在每个结果进程中调用fork,你总共有4个.然后4个进程再次打印hello,return和打印hello,共计8个hellos.