且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-01 15:04:32

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

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.