Function operation fork ()

1

Someone can explain how the fork () function works relative to the state of the variables for each child process call in this piece of code:

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

int main(void)
{
    int pid,x=2;
    if (0 == (pid =fork())) {
        fork();
        pid=fork();
        if (pid==0) {
            x--;
        }
    }
    else{
        printf("aki\n");
        execl("bin/date", "date",0);
        x=x+2;
    }

    printf("x=%d\n",x);
    exit(0);
}

I was trying to figure out but I do not know what value is passed to the child process variable x =?

    
asked by anonymous 18.04.2018 / 19:59

1 answer

1

The fork function opens a child process with a copy of the variables values of the parent process. In this example the else will be executed for the child process and x will go to 4. In the parent it will go to 1.

EDIT:
It happens that the fork when executed opens a second process and both processes execute the next line that is just after the original fork with this we have the following:

It happens the first fork in if where an assignment is made to the pid variable. The result of this is 0 that in the test condition is ok and enters the block. The first line of this block is a fork that assigns nothing to pid , so we have a child process that does not enters the else and starts executing on the next line which is another fork assigning pid . But then the parent process of that second child also executes fork by assigning pid . As one of these is the parent will assign 0 to pid while the other does not decrease the x variable.

With this we have: pid = 45750x = 2 child of a fork inside if pid = 45751x = 2 child of a fork of the other child inside the if pid = 0x = 1 original parent pid = 0x = 1 child of the original and parent of the second fork inside the if

In the child process of the original it enters else which makes x=x+2; that prints pid=45748x=4 .

    
18.04.2018 / 20:19