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?
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With