Hey i want to know what will be output of followi开发者_开发问答ng code:-
main()
{
fork();
fork();
fork();
printf("hello world");
}
I think it should print hello world 4 times. Plz help me.
it will print it 8 times (2 ^ 3): each fork generates an extra process -- so you end up with 2 processes at each step (the parent and the child) and each of them continue execution at the step right after the fork. So first fork -> 2 processes each one of these going to 2nd fork in which you generate 2 extra processes so you have now 4 processes each going into the 3rd fork where each generates an extra process -- so 8 processes going into the line with printf!
Each fork creates a new child. Each child has the same code as the parent. So the children will also fork.
So Parent has 3 children. Child1 has 2 children. Child2 has 1 child. Child11 has 1 child.
Total 8 processes. 8 printf
It will print it 2^3=8 times. Remember, every time you call fork, you are creating a child process, that child process will continue the execution from right after it got forked so it can itself also fork. The tree will look like this.
First process.
Forked1 Forked2 Forked3
Forked4---Forked5 -------------- Forked6
Forked7
So we will have total of 8 process (main process and 7 forked processes)running and printing the print statement. As a side note: if the print statement was before a fork, it would not get executed by newly forked process.
精彩评论