Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused with fork()

Tags:

c

fork

I am having a difficult time understanding what the fork() command does under different scenarios. Here is some sample code from my book:

int main() {
    int a = 12;
    int b = 9;
    int fid = fork();

    if (fid == 0) {
        a++;
    }
    else {
        wait(NULL);
        b = b - 5;
    }

    printf("program exit. a = %d, b = %d\n", a, b);
    return 0;
}

Can someone walk me through what the fork() command is doing in this case and perhaps give some more examples to clarify?

like image 800
raphnguyen Avatar asked Dec 02 '22 01:12

raphnguyen


1 Answers

                 [main]
                 a = 12
                 b = 9

                 fork()
                   |
                   |
    +--------------+--------------+
    |                             |  
    |                             |
[parent]                       [child]

fid = 1234                     fid = 0
wait(NULL)                     a++
   ...                         printf("a = 13, b = 9");
   ...                         return 0
   ...                         <exit>
b = b - 5
printf("a = 12, b = 4");
return 0
<exit>

After fork() executes there are two copies of the program. Each process gets its own copies of the variables, so there are now two a's, two b's, etc. The only difference between the two programs is the value returned from fork(): in the child process fork() returns 0; in the parent process it returns the PID of the child.

The child process increments a, prints the values of a and b, and exits.

The parent process first waits for the child process to terminate. Only after the child has finished does it continue on, subtracting 5 from b, printing out a and b, and then exiting.

The wait(NULL) ensures that the child process's printout always comes before the parent's, so you will always get the same output in a reliable order. Without it you wouldn't be able to depend on the order of the two printouts. They would be the same messages, just in an unpredictable order.

like image 110
John Kugelman Avatar answered Dec 05 '22 00:12

John Kugelman