Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sleep() delays output until end [duplicate]

Tags:

c

sleep

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

like image 532
P M Avatar asked Nov 17 '10 03:11

P M


2 Answers

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 2 is 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 setvbuf before operating on stdout, to set it to unbuffered and you won't have to worry about adding all those fflush lines to your code:

setvbuf (stdout, NULL, _IONBF, BUFSIZ);

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/3 is the relevant bit:

When a stream is unbuffered, characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block.

When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled.

When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered.

Furthermore, characters are intended to be transmitted as a block to the host environment when a buffer is filled, when input is requested on an unbuffered stream, or when input is requested on a line buffered stream that requires the transmission of characters from the host environment.

Support for these characteristics is implementation-defined, and may be affected via the setbuf and setvbuf functions.

like image 186
paxdiablo Avatar answered Nov 02 '22 22:11

paxdiablo


See this answer: Why does printf not flush after the call unless a newline is in the format string?

like image 41
kkress Avatar answered Nov 02 '22 21:11

kkress