libevent(一)定时器Demo
开始研究libevent,使用的版本是2.0.22。
实现一个定时器:每2秒执行一次printf。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <event2/event.h> #include <event2/event_struct.h> #include <time.h> int event_is_persistent; static void timeout_cb(int fd, short event, void *arg) { printf("run timeout_cb\n"); if (!event_is_persistent) { struct event *timeout = (struct event*)arg; struct timeval tv; tv.tv_sec = 2; tv.tv_usec = 0; event_add(timeout, &tv); } } int main(int argc, char **argv) { int flags; if (argc == 2 && !strcmp(argv[1], "-p")) { event_is_persistent = 1; flags = EV_PERSIST; } else { event_is_persistent = 0; flags = 0; } /* Initalize the event library */ struct event_base *base = event_base_new(); /* Initalize one event */ struct event timeout; event_assign(&timeout, base, -1, flags, timeout_cb, (void*) &timeout); struct timeval tv; tv.tv_sec = 2; tv.tv_usec = 0; event_add(&timeout, &tv); event_base_dispatch(base); return (0); }
参考资料: