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?
After
fork()executes there are two copies of the program. Each process gets its own copies of the variables, so there are now twoa‘s, twob‘s, etc. The only difference between the two programs is the value returned fromfork(): in the child processfork()returns 0; in the parent process it returns the PID of the child.The child process increments
a, prints the values ofaandb, 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 outaandb, 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.