没有’\ n’的printf()在libev 中不起作用
首先发布代码:
#define EV_STANDALONE 1 #include #include "ev.c" ev_timer timeout_watcher; struct ev_loop* loop; static void timeout_cb (EV_P_ ev_timer *w, int revents) { // puts("timeout"); printf("timeout"); ev_timer_again(loop, w); } int main (void) { printf("hello, world."); loop = EV_DEFAULT; ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.); timeout_watcher.repeat = 2.0; ev_timer_start (loop, &timeout_watcher); ev_run (loop, 0); return 0; }
跑步时发生了奇怪的事情:虽然是printf("hello, world.");
在主要function中处于第一位,但它不起作用。 但是如果我使用printf("hello, world\n");
相反,事情很好。 更进一步,我改变了printf("hello, world");
而不是puts("hello, world");
,它也有效。 那么libev对io做了什么呢? 为什么“\ n”很重要?
通常,与标准输出相关联的缓冲区是行缓冲的。 写入缓冲区的内容不会立即传输到输出。
最后, \n
会导致缓冲区内容flush
到输出。
或者,您可以在没有\n
的printf()
之后使用fflush(stdout)
,但请记住,这仅适用于输出缓冲区。
FWIW,回答为什么puts()
“工作” ,引用手册页,( 强调我的 )
puts()
将字符串s
和尾部换行符写入stdout。
puts()
提供了一个隐式换行符,因此刷新了缓冲区。