How much XD will be printed?
I ran into this weird problem while playing with fork () with one of my friends. Very simple POC code:
int main(int argc, char** argv)
{
int i = 0;
for(i=0; i<4; i++) {
printf("xd\n");
fork();
}
return 0;
}
I got a good result:
xd
xd
xd
xd
xd
xd
xd
xd
xd
xd
xd
xd
xd
xd
xd
xd was printed 15 times what I expected - the number of nodes in a 4-level full binary tree. But when we removed the "\ n" in printf, we got another completely different result:
xdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxdxd
This gave me 64 XD (my friend got 56 XD in his machine). This seems to be a somewhat stable result as I could run it many times and it gives me the same output (same as my friend).
I tried to change printf ("xd") to perror ("xd"), it gave me 15 outputs:
xd: Success
xd: Success
xd: Success
xd: Success
xd: Success
xd: Success
xd: Success
xd: Success
xd: Success
xd: Success
xd: Success
xd: Success
xd: Success
xd: Success
xd: Success
And I tried
for(i=0; i<4; i++) {
printf("xd");
fflush(stdout);
fork();
}
15 XD .
, , .
, concurrency, , fork() , i. (, , )
, , stdout, , , , , - , / .
Both of these are probably wrong as I don't know much about Linux implementations, can anyone help me explain this?
The behavior you are doing is related to the buffering mode.
Since there is no newline at the end and the output is in line-buffered mode (or full-buffered mode), so the output you see is different
You should use fflush(0);
to remove all I / O buffers before fork
You can control the buffering mode with standard C functions setvbuf()
and _IOFBF
(full buffering), _IOLBF
(line buffering) and _IONBF
(no buffering).
stdout has a buffering string, so in the first version everything printf
will be printed at once:
i=0: 1 xd i=1: 2 xd i=2: 4 xd i=3: 8 xd in sum: 15 xd
on the other hand without the \n
stdout buffer will be copied with each fork()
and thus doubles the xd count.
i=0: 1 xd, after fork 2 xd and 2 processes
i=1: 4 xd, after fork 8 xd and 4 processes
i=2: 12 xd, after fork 24 xd and 8 processes
i=3: 32 xd, after fork 64 xd and 16 processes
at the end of the main process all 64 xd's will be printed.