'Having problem Understanding fork() hierarchy tree
I have this Code that I can't understand. I understood the basics of fork() but I don't understand the Hierarchical tree for this process. The code is like this:
main()
{
fork();
if(fork()){
printf("A");
}
else{
printf("B");
}
}
The output is A A B B. How does this happen? I get it why A is printed twice but why is B printed? How does the hierarchical tree work here?
Solution 1:[1]
Okay lets "draw" the process tree created by this program (using P
for parent process, and C
for child process):
fork() ^ / \ | | P C | | /------------/ \------------\ | | fork fork ^ ^ / \ / \ | | | | P C P C | | | | /-----/ \----\ /-----/ \----\ | | | | printf("A") printf("B") printf("A") printf("B")
First there's a fork()
without condition. That means the parent and child processes both continue on the same path through the program.
Then comes the second fork()
call. Both the original parent and child does this fork. In the new fork, the new parent processes will have a non-zero return value, meaning the condition is true
and they will print "A"
. The new child processes will have a zero return value, which is false
and they will go on to print "B"
.
The exact order the processes will run is unspecified, and therefore the exact output will be unpredictable. But it will print "A"
twice and "B"
twice.
Solution 2:[2]
The output is A A B B -> Output can vary between runs because of concurrency I have this
So the logic is the following: the first fork makes one more process to execute the same program after the first fork and each of the two processes creates one more process which prints B
and then prints A
by its own soo you get 4 processes in total
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Some programmer dude |
Solution 2 | Arseny Staroverov |