用管道输送到cat [英] Piping the output to cat

查看:126
本文介绍了用管道输送到cat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下程序:

int main() 
{
printf("one\n");
write(1, "two\n", 4);
return 0;
}

然后我给出命令
。 cat
在最终输出为
的两个
一个
而不是
一个
两个
为什么???

And then i give the command ./a.out | cat at the terminal to which the output comes to be two one instead of one two Why???

推荐答案

这是因为 printf 的输出将被<$缓冲c $ c> libc , write 的输出将不会被缓冲。这是直接,对文件(stdout)的无缓冲操作

That's because printf's output will get buffered by the libc, write's output will not get buffered. It's a direct, unbuffered operation on a file (stdout)

阅读


如果stdout是终端然后将缓冲自动设置为行缓冲,否则将设置为缓冲

if stdout is a terminal then buffering is automatically set to line buffered, else it is set to buffered

因此,您实际上是在管道传输到 cat -这就是启用缓冲的原因(尝试不带 cat 来查看)

So, you are actually piping to cat - that's why buffering is enabled (try without cat to see)

要关闭缓冲问题,请使用 stdbuf 命令:

To turn off the buffering issue the stdbuf command:

stdbuf -o0 ./a.out  | cat 

顺便说一句,问一个每天都不在的人是一个很好的问题C黑客!简单而具有描述性!

By the way, that's a really good question to ask for someone who isn't an every day C hacker! Simple and descriptive!

这篇关于用管道输送到cat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆