加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么是stdout缓冲?

发布时间:2020-12-16 07:50:48 所属栏目:百科 来源:网络整理
导读:我正在尝试学习libuv api并写下面的测试: #include stdio.h#include stdlib.h#include uv.hvoid timer_cb(uv_timer_t* timer) { int* i = timer-data; --*i; if(*i == 0) { uv_timer_stop(timer); } printf("timer %dn",*i); //fflush(stdout);}int main()
我正在尝试学习libuv api并写下面的测试:
#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 %dn",*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 the setbuf and
setvbuf functions.

缓冲的类型取决于您的实现,您的实现显然在您的示例中不是线缓冲.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读