强制对管道中的 stdout 进行行缓冲 [英] Force line-buffering of stdout in a pipeline
问题描述
通常,stdout
是行缓冲的.换句话说,只要您的 printf
参数以换行符结尾,您就可以期望立即打印该行.使用管道重定向到 tee
时,这似乎不成立.
Usually, stdout
is line-buffered. In other words, as long as your printf
argument ends with a newline, you can expect the line to be printed instantly. This does not appear to hold when using a pipe to redirect to tee
.
我有一个 C++ 程序,a
,它输出字符串,总是 \n
终止,到 stdout
.
I have a C++ program, a
, that outputs strings, always \n
-terminated, to stdout
.
当它自己运行时 (./a
),一切都会如预期的那样在正确的时间正确打印.但是,如果我将它通过管道传输到 tee
(./a | tee output.txt
),它在退出之前不会打印任何内容,这违背了使用 <代码>三通代码>.
When it is run by itself (./a
), everything prints correctly and at the right time, as expected. However, if I pipe it to tee
(./a | tee output.txt
), it doesn't print anything until it quits, which defeats the purpose of using tee
.
我知道我可以通过在 C++ 程序中的每个打印操作之后添加一个 fflush(stdout)
来修复它.但是有没有更干净、更简单的方法呢?例如,是否有我可以运行的命令,即使在使用管道时,它也会强制 stdout
进行行缓冲?
I know that I could fix it by adding a fflush(stdout)
after each printing operation in the C++ program. But is there a cleaner, easier way? Is there a command I can run, for example, that would force stdout
to be line-buffered, even when using a pipe?
推荐答案
试试 unbuffer
是 expect
包的一部分.您的系统中可能已经有了它.
Try unbuffer
which is part of the expect
package. You may already have it on your system.
在你的情况下,你会像这样使用它:
In your case you would use it like this:
<代码>./a |unbuffer -p tee output.txt
(-p
用于管道模式,其中 unbuffer 从 stdin 读取并将其传递给其余参数中的命令)
(-p
is for pipeline mode where unbuffer reads from stdin and passes it to the command in the rest of the arguments)
这篇关于强制对管道中的 stdout 进行行缓冲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!