Operation of function Fork()

Asked

Viewed 408 times

1

Can someone explain how the Fork() function works relative to the state of the variables at each call to the child process on 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 understand but I do not know what value is passed to the variable of process x=?

1 answer

1


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

EDIT:
It turns out that the executed Fork opens a second process and both processes run the next line that is just after the original Fork so we have the following:

Happens the first fork in the if where an assignment is made to the variable pid. The result of this is 0 which in the test condition is ok and enters the block. The first line of this block is a fork that attributes nothing to pid, with that we have a child process that nay gets into the else and starts running on the next line which is another fork attributing to pid. But soon after the father process of that second son also executes the fork attributing to the pid. As one of these is the father will assign 0 to pid while the other does not decrease the variable x.

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

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

  • what I don’t understand is ,what is loaded for variables in the other 2 Fork()

  • @user48571 You already executed the code to see the values of the variables?

  • on my machine returns Aki pid=45748x=4 pid=45750x=2 pid=45751x=2 pid=0x=1 pid=0x=1

  • @user48571 Now with the output added more explanations

  • when I make a call to Fork, what runs in the child process also includes a new Fork() in the child process?

  • Yes because you only put the if testing the result in the first. In others made the call alone and they also work.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.