【libev】ev_io

本文介绍如何利用ev.h库实现非阻塞IO操作,并通过回调函数处理读取事件,包括初始化事件监听器、设置回调函数、启动监听器及在回调中读取STDIN缓冲区。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#include <ev.h>
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>

struct ev_loop *io_loop = NULL;
ev_io io_watcher;

static void io_cb(EV_P_ ev_io *w, int revents)
{
        char buf[128]={0};
        int count = 0;

        printf("io_cb call\n");
        sleep(1);
        count = read(STDIN_FILENO, buf, 128); // read方法可以清空STDIN_FILENO缓冲区,如果不清空该缓冲区,则会一直触发该回调。
        printf("count = %d, buf = %s\n", count, buf);

        //ev_io_stop(EV_A_ w);

        //ev_break(EV_A_ EVBREAK_ALL);
        //ev_io_init(&io_watcher, io_cb, STDIN_FILENO, EV_READ);
        //ev_io_start(io_loop, &io_watcher);
}

int main()
{
        io_loop = ev_loop_new(EVFLAG_AUTO);
        ev_io_init(&io_watcher, io_cb, STDIN_FILENO, EV_READ);
        ev_io_start(io_loop, &io_watcher);
        ev_run(io_loop, 0); // 如果不在回调中调用stop或者break方法,ev_run后面的代码就永远不会被执行。所以一般会把注册事件放到子线程中去做。

        while(1){printf("abcd");}
        printf("main() call, end\n");
        return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值