Question

I have recently started understanding fork() system call and I have written below program. The doubt that I have in below program is in its output. why does the program prints only first ten lines of the parent printf and then moves to print statement in child printf and again move back to print statements in parent printf. how does this work?

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

int main()
{
    pid_t newpid;
    int i =0;

    newpid=fork();
    if(newpid==0)
    {
        for(i=0;i<10;i++)
        {
            printf("child process pid %d number %d \n", newpid,i);
        }
    }
    else
    {

        for(i=0;i<20;i++)
        {
            printf("parent process pid %d number %d \n", newpid,i);
        }

    }
    return 0;
}

Output:

parent process pid 9224 number 0
parent process pid 9224 number 1
parent process pid 9224 number 2
parent process pid 9224 number 3
parent process pid 9224 number 4
parent process pid 9224 number 5
parent process pid 9224 number 6
parent process pid 9224 number 7
parent process pid 9224 number 8
parent process pid 9224 number 9
child process pid 0 number 0
parent process pid 9224 number 10
parent process pid 9224 number 11
parent process pid 9224 number 12
parent process pid 9224 number 13
parent process pid 9224 number 14
parent process pid 9224 number 15
child process pid 0 number 1
parent process pid 9224 number 16
child process pid 0 number 2
parent process pid 9224 number 17
child process pid 0 number 3
parent process pid 9224 number 18
parent process pid 9224 number 19
child process pid 0 number 4
child process pid 0 number 5
child process pid 0 number 6
child process pid 0 number 7
child process pid 0 number 8
child process pid 0 number 9
Was it helpful?

Solution

By means of fork() you are altogether creating a new process with its own address space. This is child process. Parent is the one which created the child. They share the same code though and the output terminal. They get independently scheduled to run by the operating system. Hence you cannot predict in what order the parents print and child's print would be seen.And they certainly won't be in order and that's why you see the prints interleaved.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top