Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting processes after fork in for loop

Tags:

c

linux

fork

I have the following code:

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

I calculated that x should be printed out 6 times: twice in the first iteration and 4 times in the second.

Instead, X is printed 8 times. Why?

like image 769
Sorin Avatar asked Feb 05 '26 08:02

Sorin


1 Answers

Because of buffering. Usually, stdout is line-buffered, so

printf("x ");

doesn't immediately write the "x " to the terminal but to the output buffer. That is copied when the process fork()s, so each of the four processes after the second iteration has two "x " in the output buffer [one from the parent/before forking in the first iteration, one from the second iteration] when it exits and eight xs are printed altogether.

Flush the buffer immediately after the printf("x "); and only six will be printed.

like image 54
Daniel Fischer Avatar answered Feb 06 '26 20:02

Daniel Fischer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!