libev如何使用epoll进行事件监听
首先来看一个简单的例子(官方文件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的函数调用:
补充:软件开发 , C语言 ,