Language: C, OS: Linux
Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
fork();
printf("hello world\n");
fork();
printf("bye\n");
return 0;
}
Output:
hello world
bye
hello world
bye
hello world
bye
hello world
bye
According to this and this , printf() buffers output until a newline is encountered
.
So why does we have 4 "hello world" in this case? (instead of 2 "hello world")
Edit : Sorry all, but like @GregHewgill said, I running this program from an environment where the output cannot be directly to the terminal, when I check it again on my computer, it just run as expected.
According to this and this, printf() buffers output until a newline is encountered.
Printing a newline usually flushes only if the output goes to a terminal device. For example:
$ ./a.out >out_file
will not flush the buffer even with the newline character. So, your expectation is flawed.
The only right way to get "desired" output (2 hello world
and 4 bye
) is to either disable buffering totally using setbuf
:
setbuf(stdout, 0);
or use fflush
:
fflush(stdout);
after each printf
call to flush explicitly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.