Search code examples
operating-systemfork

Output of Forking in C


Given PID = 4224 Why am I getting output of the following snippet of code as :

x = 10922 y = 0 I am process: 10923 x = 0 y = 2 I am process: 10922 x = 0 y = 2 I am process: 10922 x = 0 y = 0 I am process: 10924

For this code :

#include <iostream>
#include <stdio.h>
#include <unistd.h>
int main() {
    int x = 1, y = 2;
    int pid;
    x=fork();
    if(x==0){
        printf("x = %d y = %d\n", x, y);
        pid = getpid();
        printf("I am process: %d\n", pid);
    }
    y  = fork();
    if(y==0){
        printf("x = %d y = %d\n", x, y);
        pid = getpid();
        printf("I am process: %d\n", pid);
    }
    return 0;
}

What is the output of the following snippet of code


Solution

  • Lets start with this, the output of your program:

    x = 0 y = 2     
    I am process: 330161
    x = 330161 y = 0
    I am process: 330162
    x = 0 y = 0
    I am process: 330163
    

    Notice that the order is a bit different from yours. That is because which process runs first is environment dependent. So, lets fix your program up a bit to be more lucid:

    #include <stdio.h>
    #include <unistd.h>
    int main() {
        int x = 1, y = 2;
        int pid;
        x=fork();
        if(x==0){
            pid = getpid();
            printf("1:x = %d y = %d I am process %d\n", x, y, pid);
        }
        fflush(NULL);
        y  = fork();
        if(y==0){
            pid = getpid();
            printf("2:x = %d y = %d I am process %d\n", x, y, pid);
        }
        return 0;
    }
    

    By placing the printfs together with a single newline, we can rest assured that each statement belongs to one process, they are not interleaved. By adding an indicator at the beginning of the line 1:, 2: we know which printf() they came from. The fflush() prevents the child process from inheriting any partially buffered writes from stdio -- not a problem if you are on a terminal, but if you redirect to a file you might find duplicated lines. So the output on my system looks like:

    1:x = 0 y = 2 I am process 330214
    2:x = 330214 y = 0 I am process 330215
    2:x = 0 y = 0 I am process 330216
    

    From that, the first child process of the main one is 330214. The second is 330215; and the grand-child (child of child) is 330216. I hope that gives you enough to work out your answers.

    Don't be afraid to play with these example programs. It is a good way to learn about the workings of your system.