karan
karan

Reputation: 323

fork() usage not getting the correct output

I am using the following code for a fork execution

#include <stdio.h>
#include <sys/types.h>

int main()
{
    int pid;
    pid=fork();
    if(pid==0)
    {
        printf("\n child 1");
        pid=fork();
        if (pid==0)
           printf("\n child 2");
    }
    return 0;
}

The output I assume should be child1 child2

Instead I am getting

child1 child2 child1

Cannot understand the fork behaviour

Upvotes: 0

Views: 278

Answers (2)

more tension
more tension

Reputation: 3352

You need to flush stdout:

printf( "\n child 1" )
fflush( stdout );

Upvotes: 0

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215597

If you have written data to any stdio FILE before calling fork and intend to use the same FILE after fork, you must call fflush on that FILE before calling fork. Failure to do so results in undefined behavior.

See here for the formal requirements:

http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_05_01

Specifically,

Note that after a fork(), two handles exist where one existed before. The application shall ensure that, if both handles can ever be accessed, they are both in a state where the other could become the active handle first. The application shall prepare for a fork() exactly as if it were a change of active handle. (If the only action performed by one of the processes is one of the exec functions or _exit() (not exit()), the handle is never accessed in that process.)

Upvotes: 3

Related Questions