您的位置:首页 > 其它

libevent-简单的定时器

2016-01-20 21:09 330 查看
/* For sockaddr_in */
#include <netinet/in.h>
/* For socket functions */
#include <sys/socket.h>
/* For gethostbyname */
#include <netdb.h>

#include <unistd.h>
#include <string.h>
#include <stdio.h>

#include <event2/event.h>
#include <event2/util.h>
static void
callback(int,short,void*);
static const struct timeval tv={5,0};
int main(int argc, char **argv)
{
//libevent与事件循环一起工作
struct event_base* ev_base;
//创建一个event_base
ev_base=event_base_new();
if(!ev_base)
{
perror("Could not create event base!\n");
return 1;
}
struct event *cb_event;
evutil_socket_t fd;
//创建一个循环事件
//由于事件被标记为EV_TIMEOUT,即超时后事件将变为激活的
//同时事件具有EV_PERSIST,意味着即使回调被激活,事件状态还是未决的
cb_event=event_new(ev_base,fd,EV_TIMEOUT|EV_PERSIST,callback,(char*)"event message");
event_add(cb_event,&tv);
//开始事件循环
event_base_dispatch(ev_base);
//清空事件资源
event_free(cb_event);
event_base_free(ev_base);
printf("done!\n");
return 0;
}
static void
callback(int fd,short what,void* arg)
{
static int call_number=0;
const char* data=arg;
printf("%s%d\n",arg,call_number);
++call_number;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: