Interesting question though I am not sure whether it is worth while to spend a lot of time in in this kind of questions in the exam:
fork returns 0 to the child and a non zero to the parent, for this question we can assume that is always 1.
Lets number the lines of the code for easy reference:
1 if(fork()&& fork()) {
2 fork();
}
3 if(fork()||fork()) {
// There should be a fork here, to make things interesting
// What the hell we are going to put one here as the main aim is to understand
// the concept
4 fork();
}
5 printf("GATE\n");
After the first fork call the code will be like:
\\Parent
if(1 && fork()){
\\ rest same
\\Child
if(0 && fork()){
\\ rest same
And after the second fork call it will become:
\\Parent
if(1 && 1){
\\ rest same
\Child 1
if(1 && 0){
\\ rest same
\\Child 2
if(0 && 1){
\\ rest same
\\Child 3
if(0 && 1){
\\ rest same
So we have 4 processes after line number 1.
The fork at line 2 will be executed only once (by original parent). Now there are 5 processes in total.
At line number 3, after the first fork the situation will like the same as earlier, instead we now have 10 processes, 5 with 1 and 5 with 0 return values.
These 5 with 1 return value will definitely call both of the remianing forks and hence there number will be 20.
The remaining 5, will call second fork at line 3 and make the count 10, 5 with 0 and 5 with 1. These 5 will only call the fork at line 4 and hence total count will be 5+10 = 15
Adding this 15 to the 20 from above, makes the total 35 and hence the line 5 will be printed 35 times.
If we ignore the fork at line 4, as given in the question then the answer will be 20