libevent的信号处理
libevent如何做signal的集成其实很简单,使用strace工具就可以很容易知道:
比如,用alarm
产生一个定时器信号,然后使用libevent
的sigal
的接口对其进行捕获,最终进入回调函数
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#include <unistd.h>
#include <signal.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
void sig_cb(evutil_socket_t fd,short event,void *arg)
{
printf("In signal event callback\r\n");
struct event_base * base = (struct event_base *)arg;
event_base_loopbreak(base);
}
int main(int argc,char **argv)
{
struct event_base* base=event_base_new();
assert(base!=NULL);
struct event* ev=evsignal_new(base,
(evutil_socket_t)SIGALRM,
sig_cb,
base);
evsignal_add(ev,NULL);//在event_add函数中,通过ev->base获取event_base对象
alarm(5);
event_base_dispatch(base);
printf("exit...\r\n");
return 0;
}
strace ./alarm
发现会创建socketpair:
socketpair(PF_LOCAL, SOCK_STREAM, 0, [4, 5]) = 0
当信号发生时,会sendto一个消息,从而使得fd可读,epoll返回:
sendto(4, "\16", 1, 0, NULL, 0) = 1
rt_sigreturn() = -1 EINTR (Interrupted system call)
epoll_wait(3, {
{EPOLLIN, {u32=5, u64=5}}}, 32, -1) = 1
recvfrom(5, "\16", 1024, 0, NULL, NULL) = 1
<