libevent处理信号

使用evsignal_new 注册一个no-pending的事件,并指定回调函数

具体例子

#include 
#include 
#include 

using namespace std;

static void Ctrl_C(int sockfd, short what, void* arg){
	cout << "Ctrl_C" << endl;
}

static void kill(int sockfd, short what, void* arg){
    cout << " Kill " << endl;
	// 如果处于 no-pending
	event* ev = (event*) arg;
	if(!evsignal_pending(ev,NULL)){
		event_del(ev);
		event_add(ev,NULL);
	}
}

int main(int argc, char* argv[]){
	event_base* base = event_base_new();
	//添加ctrl+c 信号事件, 处于no-padding
	// evsignal_new 隐藏的状态,EV_SIGNAL | EV_PERSIST
	event* csig = evsignal_new(base, SIGINT, Ctrl_C, base);
	if(!csig){
		cerr << "SIGINT evsignal_new failed!" << endl;
		return -1;
	}
	
	//添加事件到padding
	if(event_add(csig, 0) != 0){
		cerr << "SIGINT event_add failed!" << endl;
		return -1;
	}
	
	//添加kill信号
	//非持久信号,至进入一次event_self_cbarg()传递当前的event
	event* ksig = event_new(base, SIGTERM, EV_SIGNAL, kill, event_self_cbarg());
	if(!ksig){
        cerr << "SIGTERM evsignal_new failed!" << endl;
        return -1;
    }
   
    //添加事件到padding
    if(event_add(ksig, 0) != 0){
        cerr << "SIGTERM event_add failed!" << endl;
        return -1;
    }
	
	//进入事件主循环
	event_base_dispatch(base);
	event_free(csig);
	event_base_free(base);
}

 

你可能感兴趣的:(libevent,event,epoll)