views:

29

answers:

1

Hello I am new to CGI programming in C.

What I'm looking to do is, per the title, print things dynamically. For instance, consider this code that prints out a bunch of numbers:

int main()
{
    long int l=0;

    printf("Content-Type: text/plain;charset=us-ascii\n\n");

    while(1)
    {    
        printf("%li ", l);

        if ((l%30) == 0)
            printf("\n");

        if (l == 5000)
            exit(1);

        ++l;
        usleep(3000);
    }    
}

The issue with it is that it doesn't print until the whole thing finishes. How do I go about getting things to print exactly as they would on a terminal?

+1  A: 

You need to explicitly flush your output stream. When your program's output is being redirected (such as to a file or to the input of another program like in this case), then it only gets flushed periodically when the output buffer (usually 4–64 KB or so) fills up.

To flush stdout, just call fflush(3):

if((l%30) == 0) {
    printf("\n");
    fflush(stdout);
}

Note that when the output is going to a terminal (e.g. if you just ran your program normally), then by default it is line-buffered: every time you print a newline, the output gets flushed. This makes interactive programs much easier to write, but degrades the performance of non-interactive programs. The more often you flush, the slower your program goes, so you should only flush when necessary, such as after writing one long coherent set of data but before performing a long intensive task.

Adam Rosenfield
Thanks for the response. I implemented what you said (this is just for a practice program), but it still didn't work. I suspect now that perhaps the stdout is not the stream to flush, even though I believe I have read that the streams are such as stdout goes straight over the wire in CGI programming. Gives me something to figure out on my own still but thanks for the nudge in the right direction. It is much appreciated!