787 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

3 Answers

Best answer
2 votes
2 votes

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
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

3 votes
3 votes
3 answers
1