in Operating System
1,694 views
1 vote
1 vote

main()

{

printf(" * ");

for(i=0;i<n;i++)

fork();

printf(" * ");

}

how many times * is printed??

in Operating System
1.7k views

1 Answer

2 votes
2 votes

2n  +1     

Try drawing a tree to understand how each fork works.

http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/create.html

edited by

4 Comments

 n for loops 2^n -1 child process would be created so 2^n-1 time * would be printed by child process + 2 times by parent ...in total 2^n+1 '*' would be printed.

Does it make clear...??

0
0
Yes I got it.But you said gcc gave you 10 as answer?
1
1
edited by

oh yes i didn't noticed it should be 9....:p

actually its giving different number of '*' everytime I execute.....

http://ideone.com/2hSoxN  ---> it now printed 16 *

and here https://code.hackerearth.com/7e4258A--->its 14
and I have no explanation for that.....may be its because printf buffers output and thus when child executes printf it gets displayed twice....

but i have no proper explanation for the behaviour....

0
0

Related questions