问题
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