配管到T型管时强制stdout进行线缓冲 [英] Force line-buffering of stdout when piping to tee
问题描述
通常,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
),则在退出之前它不会打印任何内容,这违背了使用tee
的目的.
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)
这篇关于配管到T型管时强制stdout进行线缓冲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!