From 9f2645cffe0dee257468a088c0a996ff6844365c Mon Sep 17 00:00:00 2001 From: adminPyf <3043130461@qq.com> Date: Sun, 13 Jun 2021 12:37:02 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=87=E4=BB=B6=E8=87=B3?= =?UTF-8?q?=20'test=5Floop'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 事件循环demo --- test_loop/makefile | 2 + test_loop/test_loop.cpp | 84 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 test_loop/makefile create mode 100644 test_loop/test_loop.cpp diff --git a/test_loop/makefile b/test_loop/makefile new file mode 100644 index 0000000..0a68368 --- /dev/null +++ b/test_loop/makefile @@ -0,0 +1,2 @@ +test_loop:test_loop.cpp + g++ $^ -o $@ -levent \ No newline at end of file diff --git a/test_loop/test_loop.cpp b/test_loop/test_loop.cpp new file mode 100644 index 0000000..b26a870 --- /dev/null +++ b/test_loop/test_loop.cpp @@ -0,0 +1,84 @@ +#include +#include +#include + +using namespace std; + +bool isexit = false; + +//sock 文件描述符 which 事件类型 arg传递的参数 +static void Ctrl_C(int sock,short which , void* arg){ + cout << "Ctrl_C" << endl; + event_base * base = (event_base *)arg; + + //执行完当前事件函数退出 + //event_base_loopbreak(base); + + //运行完所有的活动事件在退出,事件循环没有运行时,也要等运行一次在退出 + timeval t= {3,0}; //至少运行3s退出 + event_base_loopexit(base,&t); + +} + +static void Kill(int sock,short which , void* arg){ + cout << "Kill" << endl; + + event *ev = (event*)arg; + //如果处于非待决 + if(!evsignal_pending(ev,NULL)){ + event_del(ev); + event_add(ev,NULL); //再次添加进来 + } +} + +int main(int agrc,char** agrv){ + + event_base *base = event_base_new(); + + //添加信号 ctrl+c ,处于no pending 状态 + //evsignal_new 隐藏的状态 EV_SIGNAL|EV_PERSIST + event *csig = evsignal_new(base,SIGINT,Ctrl_C,base); + + if(!csig){ + cerr << "SIGNAL evsignal_new failed!" << endl; + return -1; + } + + if (event_add(csig,0) != 0){ + cerr << "SIGANL event_add failed" << endl; + } + + //添加kill信号 + //非持久事件,只进入一次 event_self_cbarg()传递当前的event + event *ksig = event_new(base,SIGTERM,EV_SIGNAL,Kill, + event_self_cbarg()); + + if(!ksig){ + cerr << "SIGNAL evsignal_new failed!" << endl; + return -1; + } + + if (event_add(ksig,0) != 0){ + cerr << "SIGANL event_add failed" << endl; + } + //进入事件主循环 + //event_base_dispatch(base); + + //EVLOOP_ONCE 等待一个事件运行,直到没有活动事件就退出 + //EVLOOP_NONBLOCK 有活动事件就处理,没有就返回0 + //event_base_loop(base,EVLOOP_NONBLOCK); + + + // while (isexit) + // { + // event_base_loop(base,EVLOOP_NONBLOCK); + // } + + //没有注册事件也不返回,用于事件后期多线程添加 + event_base_loop(base,EVLOOP_NO_EXIT_ON_EMPTY); + event_free(csig); + event_base_free(base); + + return 0; + +} \ No newline at end of file