libev的用法
本例是以linux环境c++的用法,ide用的是vs2019
一、libev的安装
我们采用的是apt-get方法(偷懒^_^),你也可以采用源码方式安装
sudo apt-get install libev-dev
二、vs 2019的库引入
我们在这里引入libev,curl和glib库,对就命令编译的格式为
g++ main.cpp -o main -lev -lcurl -lglib-2.0 -L/usr/include/glib-2.0 -L/usr/lib/aarch64-linux-gnu/glib-2.0/include/
三、使用说明
1.引入ev.h
2.初始化libev
struct ev_loop* loop; loop = EV_DEFAULT;
3.添加监听
io监听
/**读取监听**/ ev_io_init(&socket_read_watcher, socket_read_action, fd, EV_READ); ev_io_start(loop, &socket_read_watcher);
信号中断监听
/**系统信号监听**/ ev_signal_init(&signal_watcher, signal_action, SIGINT); ev_signal_start(loop, &signal_watcher);
定时任务
/**心跳监听部分start**/ ev_timer_init(&socket_time_heart_watcher, socket_heart_watcher, 5.5, 0.); ev_timer_start(loop, &socket_time_heart_watcher);
启动监听
ev_run(loop, 0);
四、示例Demo
#include <cstdio> #include <iostream> #include <time.h> #include <unistd.h> #include <ev.h> #include "main.h" using namespace std; /** 定时监听 */ ev_timer socket_time_heart_watcher; /** socket监听 */ ev_io socket_read_watcher; /** 信号 */ ev_signal signal_watcher; struct ev_loop* loop; /************************************************* Function: // 信号监听 Description: // 信号监听 @main_loop //libev *************************************************/ void signal_action(struct ev_loop* main_loop, ev_signal* signal_w, int e) { cout << "In Signal action" << endl; } /************************************************* Function: // SOCKET读监听 Description: // 读监听 @main_loop //libev *************************************************/ void socket_read_action(EV_P_ ev_io* w, int revents) { try { } catch (...) { } } /************************************************* Function: // SOCKET心跳 Description: // 心跳 @main_loop //libev *************************************************/ void socket_heart_watcher(EV_P_ ev_timer* timer, int revents) { try { cout << "i'm heart " << endl; } catch (...) { } timer->repeat = 5.0; ev_timer_again(loop, timer); } int main(int argc, char* argv[]) { cout << "start!.....\n" << endl; int i = 0; loop = EV_DEFAULT; /**网络读取监听**/ ev_io_init(&socket_read_watcher, socket_read_action, 0, EV_READ); ev_io_start(loop, &socket_read_watcher); /**系统信号监听**/ ev_signal_init(&signal_watcher, signal_action, SIGINT); ev_signal_start(loop, &signal_watcher); /**心跳监听部分start**/ ev_timer_init(&socket_time_heart_watcher, socket_heart_watcher, 5.5, 0.); ev_timer_start(loop, &socket_time_heart_watcher); ev_run(loop, 0); return 0; }