码迷,mamicode.com
首页 > 其他好文 > 详细

libevent的hello world程序

时间:2016-06-05 16:58:06      阅读:354      评论:0      收藏:0      [点我收藏+]

标签:

照着例子写了一个简单的libevent hello world代码:

#include <sys/signal.h>
#include <event.h>

void signal_cb(int fd, short event, void *arg) {
        event_base *base = (event_base*) arg;
        timeval delay = {2, 0};
        printf("Caught an interrupt signal, exit in 2 sec...\n");
        event_base_loopexit(base, &delay);
}

void timeout_cb(int fd, short event, void *arg) {
        printf("timeout\n");
}

int main() {
        event_base *base = event_init();
        event *signal_event = evsignal_new(base, SIGINT, signal_cb, base);
        event_add(signal_event, NULL);

        timeval tv = {1, 0};
        event * timeout_event = evtimer_new(base, timeout_cb, NULL);
        event_add(timeout_event, &tv);

        event_base_dispatch(base);

        event_free(timeout_event);
        event_free(signal_event);
        event_base_free(base);

}

Makefile的内容:

lhello : lhello.cpp
        g++ -o lhello lhello.cpp -levent -L/usr/local/lib -Wl,-rpath=/usr/local/lib

运行程序:

$ ./lhello 
timeout
^CCaught an interrupt signal, exit in 2 sec...

显示经过1秒,显示timeout,然后Ctrl+C之后,会打印提示,并且等待2秒后退出。

 

注意,在程序中初始化event使用了两个不同的函数,evsignal_new 和 evtimer_new,其实它们都是定义在 include/event2/event.h中的宏,都是利用event_new这个函数,并且加上不同的参数的:

#define evsignal_new(base, signum, callback, arg) \
    event_new((base), (signum), EV_SIGNAL|EV_PERSIST, (callback), (arg))

#define evtimer_new(base, callback, arg) \
    event_new((base), -1, 0, (callback), (arg))

 

libevent的hello world程序

标签:

原文地址:http://www.cnblogs.com/charlesblc/p/5561059.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!