Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fork() in c using printf [duplicate]

Tags:

c

fork

printf

There are 2 different programs, they are small for example:

int main()
{
        printf ("print hello");
        fork();
}

int main()
{
        printf ("print hello\n");
        fork();
}

output 1 is: `print helloprint hello

output 2 is:print hello

The question is, why does the one with the \n only print once, and the first one prints it twice?

like image 229
DDukesterman Avatar asked Jul 03 '13 17:07

DDukesterman


2 Answers

You're running into the buffering behaviour of your system's printf implementation. In the first case, the string is printed to a buffer, but since there's no newline (and you didn't call fflush), it's just sitting there in that buffer. Then you fork, and both forked buffers are flushed when their respective processes exit.

In the second case, the \n causes the buffer to be flushed before the fork, so there's no output remaining when the forked processes exit.

like image 129
Carl Norum Avatar answered Nov 11 '22 18:11

Carl Norum


Change:

    printf ("print hello");
    fork();

to

    printf ("print hello");
    fflush(stdout);
    fork();

By default, stdout is usually line-buffered. In your example 2) you have the guarantee that stdout is flushed before the fork but in the example 1) it may happen after the fork. Flushing stdout before the fork guarantee you to have the string printed before the fork.

like image 26
ouah Avatar answered Nov 11 '22 20:11

ouah