in Operating System
393 views
0 votes
0 votes
Consider the following program segment of C-programming language:

#include<stdio.h>

 

int main() {

 

if (fork() || fork())

 

fork();

 

printf("GATE\n");

 

return 0;

 

}

 

Number of times the above program prints 'GATE' is_?
in Operating System
by
393 views

4 Comments

Because C1 was created because of P’s fork() calling. So in the first fork() C1 being child  so return 0 and P which is parent return non zero value in the first fork().
2
2
Here in this problem the program counter stores the if statement for all child and parent process and both forks in if statement are executed by all child and parent process. Is it correct?
0
0

2 Answers

1 vote
1 vote

@jayadev

The answer is 5 ( 1 1 1 1 1 )...…

 

1. It will create two process one parent P (has process ID of child process)and other is child C1 (process ID = 0)....

2. In if statement we used OR operator( || ) and in this case second condition is evaluated when first condition is false....

3. Parent process P will return positive integer so it directly execute statement and create two more processes (one parent P and other is child C2)…

Child process C1 will return 0 so it checks for second condition and second condition again create two more processes(one parent C1 and other is child C3)…

 

4. C1 return positive integer so it will further create two more processes (one parent C1 and other is child C4). Child C3 return 0 so it will directly print 1…

 

by
0 votes
0 votes
p

                                 (>0) p--------------------------------c(=0)

                     (>0)p----------------c1(=0)-----------------c(>0)-----------------c2(=0)

                     print(gate)       print(gate)        c(>0)-----------c3(=0)     print(gate)  

                                                                  print(gate)      print(gate)  

5 times gate will be printed