Results 1 to 4 of 4

Thread: Working around stdio buffering

  1. #1
    Join Date
    Jun 2008
    Location
    Albuquerque, NM, USA
    Posts
    87

    Default 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\n");
    sleep(2);
    printf("bar\n");
    ...

    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
    It's really that much fun!
    Geeko Samurai (cc)
    My Recent Tracks

  2. #2
    Join Date
    Jun 2008
    Location
    Frisco, TX
    Posts
    1,233

    Default Re: Working around stdio buffering

    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.

  3. #3
    Join Date
    Jun 2008
    Location
    UTC+10
    Posts
    9,686
    Blog Entries
    4

    Default Re: Working around stdio buffering

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

  4. #4

    Default Re: Working around stdio buffering

    Or setvbuf().

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •