edited by
1,042 views
11 votes
11 votes
int main()
{
if(fork() == 0)
printf("GATE2018");
if(fork() == 0)
printf("GATE2018");
}

How many times GATE2018 printed?

edited by

4 Answers

Best answer
2 votes
2 votes
int main()
{
if(fork() == 0)
printf("GATE2018");  // a child process is created because fork() == 0

 if(fork() == 0)            // one parent process is created as fork() returns a non zero value, this is process id of previous child process
                                 // another child process is created as fork() == 0
printf("GATE2018");  
}                              // at this point total 3 times GATE 2018 gets printed
selected by
3 votes
3 votes

whenever the fork()=0  GATE 2018 gets printed.so, total 3 times it is printed

1 votes
1 votes

When a child process gets created, process id of the child process which is a +ve value returns to Parent process, 0 to child process, and -ve value to parent when child cretaion fails.

When Parent process executes this program:
condition will be FALSE for parent, as fork() will be replaced with +ve process id value.
hence nothing will be printed by parent process.
But newly created child process will print GATE2018 as 'if' evaluates to true for it.

Next Fork() will be executed by Parent and first child process both. here TWO new processes will be created, one by parent and second by the first child. So first child of parent will get its sibling and  first child will get its own child too.

GATE2018 will be printed twice, once by new child and second by child of child

So, in total GATE2018 will be printed thrice! 

1 votes
1 votes

Answer (3)




if(fork() == 0)   #1
printf("GATE2018");
if(fork() == 0)   #2
printf("GATE2018");

#1)   (2) processes are created .  Half of which enter into "if" . (2/2) = 1.

Therefore 1 time it is printed !

#2)  2 processes created  above come and create (4) processes now!. Half of which enter into "if". (4/2) = 2.

Therefore 2 time it is printed !

Totally (3) times it'll be printed

Answer:

Related questions

0 votes
0 votes
3 answers
1
jayadev asked Feb 1, 2022
996 views
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...
0 votes
0 votes
1 answer
2
jayadev asked Dec 7, 2021
443 views
Why the operating system has the knowledge about kernel level threads but not about user level threads?
1 votes
1 votes
1 answer
3
jayadev asked Dec 6, 2021
386 views
Does kernel level threads have separate PCB(process control block)?
9 votes
9 votes
2 answers
4
junaid ahmad asked Jul 13, 2017
865 views
if(fork() && fork()) {fork();}if(fork()||fork()) {fork();fork();}printf("XYZ");How many time XYZ gets printed ?