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

2019-01-29 14:15发布

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);
}

标签: c linux fork
3条回答
Fickle 薄情
2楼-- · 2019-01-29 14:29

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.

查看更多
Root(大扎)
3楼-- · 2019-01-29 14:36

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?

查看更多
smile是对你的礼貌
4楼-- · 2019-01-29 14:51

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.

查看更多
登录 后发表回答