Possible Duplicate:
Why does printf not flush after the call unless a newline is in the format string? (in C)
I’m using the sleep() function in C, and am running into a problem: I wasn’t sure that this was the problem so I boiled the entire code down to this:
int main() {
printf("1");
sleep(3);
printf("2");
return 0;
}
What I thought this should produce is 1 .. wait for 3 seconds .. 2. Instead the program waits for 3 seconds and then prints 12. Is there any way to use the sleep function so that I get the first output?
Thanks
It’s not actually the sleep function which is delaying the output, it’s the buffering nature of the standard output stream. The output of
2is almost certainly also delayed until your program exits main but the delay there is so small you’re not noticing it.Standard output is line buffered if it can be detected to refer to an interactive device (otherwise it’s fully buffered).
If you
fflush (stdout)after every output call that you want to see immediately, that will solve the problem.Alternatively, you can use
setvbufbefore operating onstdout, to set it to unbuffered and you won’t have to worry about adding all thosefflushlines to your code:Just keep in mind that may affect performance quite a bit if you’re sending the output to a file. Also keep in mind that support for this is implementation-defined, not guaranteed by the standard.
ISO C99 section
7.19.3/3is the relevant bit: