Unexpected behavior when printf is used after fork() and the parent is on wait()

Viewed 142

I have the following 2 sets of code that output differently. [outputting to the terminal]

Code 1:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main ()
{ 
    printf("before the fork\n");
    fflush(stdout);
    int pid=fork();
    printf("after the fork\n");

    if (pid == 0)  
    {
        sleep(1);
        printf("I'm child");
    }
    else   
    {
        wait();
        printf ("I'm parent");
    }
    exit(0);
}

Output 1:

before the fork
after the fork
after the fork
I'm child

Now only the printf after the fork is commented and we see the printf after wait() for the parent process works as expected.

Code 2:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main ()
{ 
    printf("before the fork\n");
    fflush(stdout);
    int pid=fork();
    // printf("after the fork\n");

    if (pid == 0)  
    {
        sleep(1);
        printf("I'm child");
    }
    else   
    {
        wait();
        printf ("I'm parent");
    }
    exit(0);
}

Output 2:

before the fork
I'm childI'm parent

I am confused as in how the printf after the fork() messes up the output.

Note the following output too

Code 3:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main ()
{ 
    printf("before the fork\n");
    fflush(stdout);
    int pid=fork();
    printf("after the fork\n");

    if (pid == 0)  
    {
        sleep(1);
        printf("I'm child");
    }
    else   
    {
        //wait();
        printf ("I'm parent");
    }
    exit(0);
}

Output 3:

before the fork
after the fork
I'm parentafter the fork
I'm child

Any idea why this discrepancy?

1 Answers

It's not because of the printf("after the fork\n"); that you get different output.

The reason is when fork() system call is invoked you create a child process. And the both the parent process and child process both are running concurrently. So we don't know which would get priority (maybe parent or child).

My output in a online compiler.

In code2, the child process got the preference and so it executes first, followed by parent process.

Also in code 3, wait() system call is invoked, so if parent process gets the preference , it gets executed till the wait(). After that the child process is executed and after termination of child process, the parent process continues from where it left.

refer this for more understanding

Related