c - printf newline 有行缓冲区吗?

标签 c linux fork

语言: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

根据 thisthis , 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/

相关文章:

c - 动态分配数组说明

linux - Sed,在两行之间解析,但只打印有限的行

apache - Fork shell 脚本(不是 &)

fork 程序的 C++ shell 问题

arrays - 从 perl 中的其他数组中 grep 一个数组

C++ 删除具有有效地址的指针

python - *** 错误 `python' : munmap_chunk(): invalid pointer: 0x00007fdfb8c28950 ***

python - 如何在 C/C++ 中调用 Python 函数的简单示例

c - 双重间接寻址和传递给函数的结构

c - 不小心创建了巨大的文件