sleep() delays output until end [duplicate]

旧巷老猫 提交于 2019-11-29 14:02:45

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.

The standard library buffers output, waiting until there is enough output to amortize the cost of the actual printing.

You must flush the buffer after each printing to ensure that it will be printed before the code continues:

fflush(stdout);

Try:

int main() {

  printf("1");  fflush(stdout);
  sleep(3);
  printf("2");  fflush(stdout);

  return 0;
}

to force the io library to empty it's buffers before the sleep and return statements.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!