printf anomaly after "fork()"

Posted by pechenie on Stack Overflow See other posts from Stack Overflow or by pechenie
Published on 2010-03-27T19:37:14Z Indexed on 2010/03/27 19:43 UTC
Read the original article Hit count: 233

Filed under:
|
|
|
|

OS: Linux, Language: pure C

I'm moving forward in learning C progpramming in general, and C programming under UNIX in a special case :D So, I detected a strange (as for me) behaviour of the printf() function after using a fork() call. Let's take a look at simple test program:

#include <stdio.h>
#include <system.h>

int main()
{
    int pid;
    printf( "Hello, my pid is %d", getpid() );

    pid = fork();
    if( pid == 0 )
    {
            printf( "\nI was forked! :D" );
            sleep( 3 );
    }
    else
    {
            waitpid( pid, NULL, 0 );
            printf( "\n%d was forked!", pid );
    }
    return 0;
}

In this case the output looks like:

Hello, my pid is 1111
I was forked! :DHello, my pid is 1111
2222 was forked!

Why the second "Hello" string occured in the child's output? Yes, it is exactly what the parent printed on it's start, with the parent's pid.

But! If we place '\n' character in the end of each string we got the expected output:

#include <stdio.h>
#include <system.h>

int main()
{
    int pid;
    printf( "Hello, my pid is %d\n", getpid() ); // SIC!!

    pid = fork();
    if( pid == 0 )
    {
            printf( "I was forked! :D" ); //removed the '\n', no matter
            sleep( 3 );
    }
    else
    {
            waitpid( pid, NULL, 0 );
            printf( "\n%d was forked!", pid );
    }
    return 0;
}

And the output looks like:

Hello, my pid is 1111
I was forked! :D
2222 was forked!

Why does it happen? Is it ... ummm ... correct behaviour? Or it's a kind of the 'bug'?

© Stack Overflow or respective owner

Related posts about fork

Related posts about printf