Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does this fork() work

Tags:

c++

c

linux

can you tell me, why is output of this program this: 1 2 2 5 5 3 4 5 4 5 3 4 5 4 5

And quick explanation why is that like this? Thanks

main()
{
    printf("1\n");
    fork();
    printf("2\n");
    if(fork()==0)
    {
        printf("3\n");
        fork();
        printf("4\n");
    }
    printf("5\n");
}
like image 484
Michael Avatar asked Feb 08 '26 03:02

Michael


1 Answers

The output of your program, assuming no calls to fork fail, should be thought of like this:

1
2     2
  3     3
  4 4   4 4
5 5 5 5 5 5

Each column represents the output of one process. They all get serialized onto stdout in some random order, subject only to the following constraints: within a column, each character cannot appear before the character immediately above it; the topmost character in each column cannot appear before the character above and to the left of it.

Note that right now your program is relying on the C library noticing that stdout is a terminal and therefore setting it to line-buffered. If you run the program with stdout redirected to a file or pipe you are likely to get rather different output, e.g.

$ ./a.out | tr '\n' ' '
1 2 5 1 2 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5

... because in that case all of the output is buffered until returning from main, and the buffers are copied into each child process. Adding

setvbuf(stdout, 0, _IONBF, 0);

before the first printf statement will prevent duplication of output. (In this case you could get away with _IOLBF instead, but _IONBF is safer for code like this.)

like image 140
zwol Avatar answered Feb 13 '26 17:02

zwol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!