So I have to find the output of this code which is using the fork()
method. I thought the output was 5 "hello" s but instead I got 8. Why is that? This is the code:
#include "csapp.h"
void doit()
{
Fork();
Fork();
printf("hello\n");
return;
}
int main()
{
doit();
printf("hello\n");
exit(0);
}
Here's what your code is doing:
main->doit()->Fork()->Fork()->printf()->return->printf()->exit()
| |
| ----->printf()->return->printf()->exit()
|
----->Fork()->printf()->return->printf()->exit()
|
----->printf()->return->printf()->exit()
As you can see, you have a total of 8 calls to printf()
.
It would have been easier for you to see what was going on if you chose to print different strings in your main
and doit
functions.
Setting breakpoint on each printf()
call is another effective strategy for figuring out these kinds of problems.
First you call fork and your one process forks into two. Then you call fork in each resulting process and you have a total of 4. Then the 4 processes print hello, return, and print hello again, for a total of 8 hellos.
You create process #1. Before printing anything, process #1 calls fork()
and generates a clone that we will call process #2. Both processes #1 and #2 call fork()
again, cloning into processes #3 and #4. Now you have 4 processes and each one of them will print hello
twice. How many hello
are printed?