why does this fork() out put produce 8 instead of 5?

后端 未结 3 801
不思量自难忘°
不思量自难忘° 2020-12-22 14:01

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

相关标签:
3条回答
  • 2020-12-22 14:16

    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()
    

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

    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.

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

    0 讨论(0)
  • 2020-12-22 14:22

    You create process #1. Before printing anything, process #1 calls fork() and generates a clone that we will call process #2. Both processes #1 and #2 call fork() again, cloning into processes #3 and #4. Now you have 4 processes and each one of them will print hello twice. How many hello are printed?

    0 讨论(0)
  • 2020-12-22 14:24

    First you call fork and your one process forks into two. Then you call fork in each resulting process and you have a total of 4. Then the 4 processes print hello, return, and print hello again, for a total of 8 hellos.

    0 讨论(0)
提交回复
热议问题