简体   繁体   中英

Why doesn't stdbuf line buffer the output of some simple c programs

I'm trying to use stdbuf to line buffer the output of a program but I can't seem to make it work as I would expect. Using this code:

#include <stdio.h>
#include <unistd.h>

int main (void)
{
    int i=0;
    for(i=0; i<10; i++)
    {
        printf("This is part one");
        fflush(stdout);
        sleep(1);
        printf(" and this is part two\n");
    }
    return 0;
}

I see This is part one , a one second wait then and this is part two\\nThis is part one .

I expected that running it as

stdbuf --output=L ./test.out

would cause the output to be a 1 second delay and then This is part one and this is part two\\n repeating at one second intervals. Instead I see the same output as in the case when I don't use stdbuf.

Am I using stdbuf incorrectly or does the call to fflush count as "adjusting" the buffering as described in the sdtbuf man page ?

If I can't use stdbuf to line buffer in this way is there another command line tool that makes it possible?

Here are a couple of options that work for me, given the sample code, and run interactively (the output was to a pseudo-TTY):

./program | grep ^
./program | while IFS= read -r line; do printf "%s\n" "$line"; done

In a couple of quick tests, both output a complete line at a time. If you need to do pipe it further, grep 's --line-buffered option should be useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM