Piping the output to cat

 ̄綄美尐妖づ 提交于 2019-12-23 02:29:30

问题


I have the following prog written:

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

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???


回答1:


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)

Read this:

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

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

To turn off the buffering issue the stdbuf command:

stdbuf -o0 ./a.out  | cat 

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




回答2:


As hek2mgl pointed out, it's because of buffering. You can put fflush(stdout) after the printf if you want to force things.



来源:https://stackoverflow.com/questions/16258019/piping-the-output-to-cat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!