C CGI Program: how to print dynamically?
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 wo开发者_开发知识库uld on a terminal?
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.
精彩评论