照着例子写了一个简单的libevent hello world代码:
#include#include 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
2016.09.28 新加的内容
以下是丰富些的Makefile,其中 $@ 代表目标, $^ 代表所有依赖, $< 代表第一个依赖。
CXX=/opt/compiler/gcc-4.8.2/bin/g++INCPATH= \ /home/work/.jumbo/include/DEP_LDFLAGS= \ -L/home/work/.jumbo/lib/DEP_LDLIBS= \ -levent \ -lpthreadTARGET= lhelloall : $(TARGET)$(TARGET) : *.cc $(CXX) -o $@ $^ -I$(INCPATH) $(DEP_LDFLAGS) $(DEP_LDLIBS).PHONY: all cleanclean : rm -rf $(TARGET)
运行程序:
$ ./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))