Working around stdio buffering

I have tried to simplify this problem as much as possible. Basically, I have a Java program that uses java.lang.Process which executes a simple C program.

/* test.c */

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

int main()
{
printf("foo
");
sleep(2);
printf("bar
");

The produces a problem of waiting until the process has exited to receive anything from the process’s streams. Unless I call fflush(stdio); after each printf().

The only thing the Java portion of the application is doing is piping stdout and stderr to the Java stream handlers. So basically, the program is getting piped. For instance, you can use the compiled above C code, execute, and pipe it to the command tee. You can see that the output from the C program is being buffered until it exits. Then tee spits out all the output.

How do I work around this buffering without putting fflush(stdio); calls after thousands of printf()'s

benstein wrote:

> How do I work around this buffering without putting fflush(stdio);
> calls after thousands of printf()'s

You could write to stderr instead.

If your output is line oriented, you can use setlinebuf(3) to flush output after each line.

Or setvbuf().