一,基本使用场景与数据流转过程
1、基本使用场景
Libevent的使用比较的简单,基本上就是需要下面几步就可以
1)创建一个struct event_base对象
2)注册要监控的事件以及设置对应的回调函数
3)开启事件循环
下面是一个具体的示例,如下:
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <event.h>
#include <evutil.h>
static void timeout_cb(evutil_socket_t fd, short what, void *arg)
{
printf("begin to exec timeout_cb.\n");
}
int main(int argc, char **argv)
{
struct event timeout;
/* 0表示只执行一次,EV_PERSIST表示定时器超时后继续等待超时 */
int flags = 0;
/* Initalize the event library */
struct event_base *base = event_base_new();
/* Initalize one event */
event_assign(&timeout, base, -1, flags, timeout_cb, (void*) &timeout);
/* 设置超时时长 */
struct timeval tv;
evutil_timerclear(&tv);
tv.tv_sec = 2;
/* 添加事件 */
event_add(&timeout, &tv);
/* 开启事件循环 */
event_base_dispatch(base);
return 0;
}
2、事件流转过程
本章节主要讲解从事件被激活到执行业务侧回调,整个过程数据的流转,如下: