libev如何使用epoll进行事件监听

转载注明出处:http://blog.csdn.net/lengzijian/article/details/8331136

 

首先来看一个简单的例子(官方文件ev.pod中可以找到)

#include  <ev.h>

#include  <stdio.h>

 

ev_io  stdin_watcher;

ev_timer  timeout_watcher;

 

static  void

stdin_cb(EV_P_  ev_io *w, int revents)

{

    puts("stdin ready");

    ev_io_stop(EV_A_ w);

    ev_break(EV_A_ EVBREAK_ALL);

}

 

static  void

timeout_cb(EV_P_  ev_timer *w, int revents)

{

    puts("timeout");

    ev_break(EV_A_ EVBREAK_ONE);

}

 

int  main()

{

    struct ev_loop *loop = EV_DEFAULT;

   

    ev_io_init(&stdin_watcher, stdin_cb,  0, EV_READ);

    ev_io_start(loop, &stdin_watcher);

   

    ev_timer_init(&timeout_watcher,  timeout_cb, 5.5, 0. );

    ev_timer_start(loop,  &timeout_watcher);

    ev_run(loop,0);

    return 0;

}

我们只关心如下几句:

struct  ev_loop *loop = EV_DEFAULT;

ev_io_init(&stdin_watcher,  stdin_cb, 0, EV_READ);

ev_io_start(loop,  &stdin_watcher);

ev_run(loop,  0);

首先来看ev_io_init中做了些什么操作:

 

ev.h文件中

#define  ev_io_init(ev,cb,fd,events)         

    do { ev_init ((ev), (cb)); ev_io_set  ((ev),(fd),(events)); } while (0)

   

#define  ev_init(ev,cb_) do {                     \

  ((ev_watcher *)(void  *)(ev))->active  =       \

  ((ev_watcher *)(void *)(ev))->pending =  0;    \

  ev_set_priority ((ev), 0);                    \

  ev_set_cb ((ev), cb_);                        \

} while  (0)

 

#define  ev_io_set(ev,fd_,events_)          

    do { (ev)->fd = (fd_); (ev)->events  = (events_) | EV__IOFDSET; } while (0)

 

#define  ev_set_cb(ev,cb_)                  

    ev_cb (ev) = (cb_)

 

#define  ev_cb(ev)                           

    (ev)->cb /* rw */

通过定义可以看出ev_io_init主要操作时:

&stdin_watcher->active=stdin_watcher->pending=0

&stdin_watcher->priority=0

&stdin_watcher->cb=stdin_cb(函数)

&stdin_watcher->fd

&stdin_watcher->events=EV_READ|EV__IOFDSET

同样,ev_io_start做了一些赋值操作,这里不过多讲解;

 

下面通过一张函数调用图来展libev的函数调用:

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值