语言:C,操作系统:Linux
代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
fork();
printf("hello world\n");
fork();
printf("bye\n");
return 0;
}
输出:
hello world
bye
hello world
bye
hello world
bye
hello world
bye
根据 this和 this , printf() 缓冲输出直到遇到换行符
。
那么为什么在这种情况下我们有 4 个“hello world”? (而不是 2 个“hello world”)
编辑:抱歉,就像@GregHewgill 所说的那样,我从一个输出不能直接到终端的环境中运行这个程序,当我在我的电脑上再次检查它时,它只是运行正如预期的那样。
最佳答案
According to this and this, printf() buffers output until a newline is encountered.
打印换行符通常只有在输出到终端设备时才会刷新。 例如:
$ ./a.out >out_file
即使有换行符也不会刷新缓冲区。所以,您的期望是有缺陷的。
获得“所需”输出(2 hello world
和 4 bye
)的唯一正确方法是使用 setbuf
完全禁用缓冲:
setbuf(stdout, 0);
或使用 fflush
:
fflush(stdout);
在每次显式刷新 printf
调用之后。
关于c - printf newline 有行缓冲区吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43052715/