unix - 强制管道中标准输出的行缓冲

标签 unix buffer pipe stdout tee

通常,stdout 是行缓冲的。换句话说,只要您的 printf 参数以换行符结尾,您就可以立即打印该行。当使用管道重定向到 tee 时,这似乎不成立。

我有一个 C++ 程序 a,它将始终以 \n 结尾的字符串输出到 stdout

当它自行运行时(./a),所有内容都会按预期在正确的时间正确打印。但是,如果我将其通过管道传输到 tee (./a | tee output.txt),它在退出之前不会打印任何内容,这违背了使用 T恤

我知道我可以通过在 C++ 程序中的每个打印操作之后添加 fflush(stdout) 来修复它。但有没有更干净、更简单的方法呢?例如,是否有一个我可以运行的命令,即使在使用管道时也会强制 stdout 进行行缓冲?

最佳答案

你可以尝试stdbuf

$ stdbuf --output=L ./a | tee output.txt

手册页的(大)部分:

  -i, --input=MODE   adjust standard input stream buffering
  -o, --output=MODE  adjust standard output stream buffering
  -e, --error=MODE   adjust standard error stream buffering

If MODE is 'L' the corresponding stream will be line buffered.
This option is invalid with standard input.

If MODE is '0' the corresponding stream will be unbuffered.

Otherwise MODE is a number which may be followed by one of the following:
KB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.
In this case the corresponding stream will be fully buffered with the buffer
size set to MODE bytes.

但请记住这一点:

NOTE: If COMMAND adjusts the buffering of its standard streams ('tee' does
for e.g.) then that will override corresponding settings changed by 'stdbuf'.
Also some filters (like 'dd' and 'cat' etc.) dont use streams for I/O,
and are thus unaffected by 'stdbuf' settings.

您没有在 tee 上运行 stdbuf,而是在 a 上运行它,所以这不会影响您,除非您在 a 的源中设置 a 的流的缓冲。

此外,stdbuf 不是 POSIX,而是 GNU-coreutils 的一部分。

关于unix - 强制管道中标准输出的行缓冲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11337041/

相关文章:

linux - 在没有 fflush(stdout) 的情况下将 block 缓冲数据写入文件

Python:我是否需要在管道读取循环中捕获 EINTR

c - 识别程序 "before"和 "after"管道中的程序来自同一个 "toolset"

go - 如何使用 Pipes 分配额外的 ExraFile 以拥有多个输出流?

perl - 为什么Perl的glob对于其他每个调用都返回undef?

linux - 如何将 "read -p"之后的文字加粗?

c - 有关缓冲、getchar() 和 scanf() 的问题吗?

c - 返回c中的缓冲区

python - 如何在 5 分钟后退出 Python 脚本

mysql - 为什么我尝试创建 MySQL 数据库时权限被拒绝?