I am confused by the fork() function in C/C++. Given the following code:
void fork2()
{
printf("LO\n");
fork()
printf("L1\n");
fork();
printf("Bye!\n");
}
Lecture slides give the following diagram
______Bye
___L1|______Bye
| ______Bye
L0|___L1|______Bye
To me, this diagram doesn't make any sense. I expect that each call to fork will result in a call to printf("LO\n")
. Or am I wrong?
You are wrong. When forking, both the parent and child process continue from the same place - after the call to fork()
, not at the start of the function. It's easy to verify this behaviour - change your function's name to main()
and then compile and run it:
#include <unistd.h>
#include <stdio.h>
int main(int argc, char **argv)
{
printf("LO\n");
fork();
printf("L1\n");
fork();
printf("Bye!\n");
return 0;
}
Output:
LO
L1
Bye!
L1
Bye!
Bye!
Bye!
There's nothing like actually trying something to figure out how it works...
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