I have the code below:
int main()
{
for (int i = 0; i < 3; i++) {
int t = fork();
if (t == 0) {
printf("child %d id: %ld from pid: %ld\n", i, (long)getpid(), (long)getppid());
exit(0);
}
else if (t > 0) {
wait(NULL);
printf("father %d id: %ld from pid: %ld\n", i, (long)getpid(), (long)getppid());
}
}
return(0);
}
When I run the output is:
And when I delete the "\n" in the printf when t>0, the output is:
How does the second output print more than the first one? Please!!
Sorry, I realized that this is problem about buffer in C and I just come accross this in my multithread assignment while I'm newbie in C and don't know about this yet. I just think it comes from multithread's problem so I ask here.
You need to remember that printf
does not necessarily cause any data to be written. Instead, printf
just writes data into an internal buffer that is flushed as needed.
Let's simplify the code a bit and unroll the loop to examine what's happening
int
main(void)
{
int t, i = 0;
t = fork();
if( t == 0 ) {
printf("child %d id: %ld from pid: %ld\n",
i, (long)getpid(), (long)getppid());
exit(0);
} else if( t > 0 ) {
wait(NULL);
printf("parent %d id: %ld from pid: %ld",
i, (long)getpid(), (long)getppid());
}
/* The output buffer now contains "parent N id ..."
but the parent has not yet written any data. */
i += 1;
t = fork();
if( t == 0 ) {
/* Here, the output buffer still contains "parent N id ..." */
printf("child %d id: %ld from pid: %ld\n",
i, (long)getpid(), (long)getppid());
/* The newline above causes the buffer to be flushed,
so now this child writes "parent N id ...child M id: ..." */
exit(0);
...
If you include the \n
in the parent's printf, that causes (in some situations) the output buffer to be flushed so that it is empty when you call fork
and the child does not write the additional data. Notice that if you redirect the output to a file, you may get different behavior since the \n
may not cause a flush in that scenario. If you want to ensure that the buffers are flushed at any given point, call fflush
.