The Gateway to Computer Science Excellence
+2 votes
int main()
{     for(i=0;i<2;i++)
          if(fork()==0) printf("hello");
in Operating System by (411 points) | 1k views

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.

1 Answer

+15 votes
Best answer

Lets unroll the loop to explain easily

int main()
    if(fork() == 0) //After here there are 2 processes
    if(fork() == 0) //After here there are 4 processes

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

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


Arjun sir plz check dis 


@arjun sir

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

i thought answer should be 2+4


and plz check this:


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?

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

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.

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

pls check

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,737 questions
57,373 answers
105,289 users