#include <stdio.h> #include <stdlib.h> #include <uv.h> void timer_cb(uv_timer_t* timer) { int* i = timer->data; --*i; if(*i == 0) { uv_timer_stop(timer); } printf("timer %d\n",*i); //fflush(stdout); } int main() { uv_loop_t* loop = uv_default_loop(); uv_timer_t* timer = malloc(sizeof(uv_timer_t)); uv_timer_init(loop,timer); int i = 5; timer->data = &i; uv_timer_start(timer,timer_cb,1000,2000); uv_run(loop,UV_RUN_DEFAULT); printf("Now quitting.\n"); uv_close(timer,0); uv_loop_close(loop); return 0; }
运行时,程序完成运行之前不显示任何输出,然后立即显示所有输出.如果我取消注释fflush行它按预期工作,每2秒写一次.
有人可以向我解释一下吗?为什么stdout在换行之后不会刷新,如here和其他地方所述?为什么需要手工冲洗?
解决方法
每7.21.3文件,C Standard的第3段:
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 thesetbuf
and
setvbuf
functions.
缓冲的类型取决于您的实现,您的实现显然在您的示例中不是线缓冲.