c - Counting processes after fork in for loop -


i have following code:

for(i=1; i<=2; i++) {     fork();     printf("x ");    } 

i calculated x should printed out 6 times: twice in first iteration , 4 times in second.

instead, x printed 8 times. why?

because of buffering. usually, stdout line-buffered, so

printf("x "); 

doesn't write "x " terminal output buffer. copied when process fork()s, each of 4 processes after second iteration has 2 "x " in output buffer [one parent/before forking in first iteration, 1 second iteration] when exits , 8 xs printed altogether.

flush buffer after printf("x "); , 6 printed.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Socket.connect doesn't throw exception in Android -

iphone - How do I keep MDScrollView from truncating my row headers and making my cells look bad? -