in Operating System
786 views
4 votes
4 votes
What is the output of the following program?

main(){

      printf("Hi");

      fork();

 

}

a) HiHi

b) Hi

c) nothing will be printed

d) none of the above
in Operating System
by
786 views

2 Comments

B is the answer. After the fork, child will be created but as there is no instruction to follow child will be ended, so parent too.

Note: fork doesn't work like recursion.
2
2

Answer given is option A. 

with this explanation

1
1

3 Answers

2 votes
2 votes
Best answer

Ran the  code and verified, prints "HiHi" which was surprising for me. Turns out the concept of buffer is correct, when in the parent printf is executed, as there is no \n in the end, buffer is not flushed and after the fork buffer is copied to the child also.

After the fork there is no statement and hence both parent and child exits. The buffer is flushed at the time of exit, both of which had "Hi" and hence "HiHi" is printed on the screen.

A very nice explanation along with a better example can be found here:

https://stackoverflow.com/questions/2530663/printf-anomaly-after-fork

selected by
2 votes
2 votes

Option B is correct.

1 comment

not correct
0
0
0 votes
0 votes

The answer is A) HiHi
Number of child processes created = 2^n -1

Here fork is called only one time hence child process  = 2 -1 = 1

Hence First Hi from the parent process and the second one from the child. 

If there would have been 2 fork then child process would have been 3 so hence total 4 x Hi ----> "HiHiHiHi"

edited by

Related questions