0

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

2 Answers 2

3

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.)

Sign up to request clarification or add additional context in comments.

Comments

0

You need to flush stdout:

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

2 Comments

Also note that the issue would never have arisen had OP not been practicing the ridiculous "put your \n's at the beginning of the message" anti-pattern.
An interesting side-effect of line buffering, then?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.