libev的用法
阅读原文时间:2023年07月08日阅读:5

本例是以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
#include
#include
#include

#include

#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;  

}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器