1k views
#include<stdio.h>
#include<unistd.h>
int main()
{     for(i=0;i<2;i++)
{
if(fork()==0) printf("hello");
}
}
| 1k views
+2

3 is the correct answer both children and the grand child of the parent process will print hello as shown below, but make sure to flush the buffer.

Lets unroll the loop to explain easily

int main()
{
if(fork() == 0) //After here there are 2 processes
printf("Hello");
if(fork() == 0) //After here there are 4 processes
printf("Hello");
}

When a process calls fork(), a copy of that process is made (like a clone) and that copy (called a child) also starts execution from the point of call of fork (starts executing the following instruction). The only difference for these 2 processes is the return value of the fork -- which is 0 for the child one and non-zero for the parent (it will be the child pid). Thus in the given code, child only does the printing.

After first fork, we have 2 processes and one of them prints.

After the second fork, we have $2\times2 = 4$ processes, and 2 of them prints.

So, totally we get $1 + 2 = 3$ "hello".

Now, there is a catch here, as I told when fork is called a copy of the process is made. This includes every thing that is part of the process including file descriptors and buffers. So, if the output buffer is not flushed before fork, even that is copied to the child process and output gets printed more times than expected. A quick fix for this is to print "hello\n" than just "hello". (Still remember my B.Tech. day when a whole day was spent on this issue).

by Veteran (431k points)
selected by
+1

So, sir for that output buffer problem , can we replace printf with "write" , printf is buffered and write is unbuffered .

+2
0

Arjun sir plz check dis

0

@arjun sir

is it like only parent processes in each case prints??

i thought answer should be 2+4

=6

and plz check this:

https://gateoverflow.in/65877/fork#a65887

+2
No, only the child prints, because fork() returns 0 for child process and this condition is there in program for printing. Is there any confusion in the other question explanation?
+1

yes, I can see this expanation which is conflict of this:

https://gateoverflow.in/65877/fork#a65887

0
oh..sorry sir

I got it...yes only child will print

at i =0, two processes are there (one is parent let p1 and other is its child let p11)

then at i=1, we will have p1 and its child let p12 , p11 and its child p112

so we have child processes as p11, p12, p112 for which fork() will return 0 hence it will print 3 times.
0

@ Arjun sir , i am trying to execute above code but i am getting "hello" 4 times, i am pasting url

pls check