Need to know how fork works?

前端 未结 7 1890
[愿得一人]
[愿得一人] 2020-12-15 13:32

I am trying the following C code:

int main()
{
    printf(\"text1\\n\");
    fork();
    printf(\"text2\\n\");
    return 0;
}

I was expect

7条回答
  •  一个人的身影
    2020-12-15 14:12

    fork clones the current process. The new process will "start" at the fork call, not at the start of main as you seem to expect. Thus when you print the first time there is 1 process, then when you fork there are two.

    Since you are forking after printing "text1", it is only printed once.

    In the second example the duplicated output is due to output buffering - printf doesn't actually output anything to the screen until it is flushed or it hits a newline ('\n').

    Consequently the first call to printf actually just wrote data to a buffer somewhere, the data was then copied into the second process' address space, and then the second call to printf would have flushed the buffer, complete with "text1" in both buffers.

提交回复
热议问题