libev是用C语言编写的高性能、全功能事件循环库,支持select,poll模型,也支持linux特定的epoll模型,一个小巧、易用的库。
环境准备:ubuntu
一、libev库支持的功能
官方文档:http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod
阅读官方文档,可以了解到libev支持事件循环和观察器。
事件循环
ev_loop //事件循环
观察器
ev_io //IO读写
ev_timer //定时器
ev_periodic //周期任务
ev_signal //信号处理
ev_child //子进程状态
ev_stat //文件属性变化
ev_async //激活线程
ev_fork //开辟进程
ev_embed //嵌入式事件循环
ev_idle //每次event loop空闲触发事件
ev_prepare //每次event loop之前事件
ev_check //每次event loop之后事件
ev_cleanup //event loop退出触发事件
二、libev库的编译和安装
libev的git仓库:https://github.com/enki/libev
1、新建一个libev_test目录,将libev-4.24.tgz文件放进去。
2、解压libev-4.24.tgz文件,并进入解压后的目录。
依次执行下面命令
./configure --prefix=$HOME"/test/libev_test/usr/local/"
make
make install
编译安装完后,对应的目录下有如下文件:
分别是头文件、动态库和man手册
交叉编译类似,需要修改编译链等。
三、libev库的使用例子
官方提供的代码示例,test.c放到libev_test目录下。
// a single header file is required
#include <ev.h>
// for puts
#include <stdio.h>
// every watcher type has its own typedef'd struct
// with the name ev_TYPE
ev_io stdin_watcher;
ev_timer timeout_watcher;
// all watcher callbacks have a similar signature
// this callback is called when data is readable on stdin
static void stdin_cb(EV_P_ ev_io *w, int revents) {
puts("stdin ready");
// for one-shot events, one must manually stop the watcher
// with its corresponding stop function.
ev_io_stop(EV_A_ w);
// this causes all nested ev_run's to stop iterating
ev_break(EV_A_ EVBREAK_ALL);
}
// another callback, this time for a time-out
static void timeout_cb(EV_P_ ev_timer *w, int revents) {
puts("timeout");
// this causes the innermost ev_run to stop iterating
ev_break(EV_A_ EVBREAK_ONE);
}
int main(void) {
// use the default event loop unless you have special needs
struct ev_loop *loop = EV_DEFAULT;
// initialise an io watcher, then start it
// this one will watch for stdin to become readable
ev_io_init(&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ);
ev_io_start(loop, &stdin_watcher);
// initialise a timer watcher, then start it
// simple non-repeating 5.5 second timeout
ev_timer_init(&timeout_watcher, timeout_cb, 5.5, 0.);
ev_timer_start(loop, &timeout_watcher);
// now wait for events to arrive
ev_run(loop, 0);
// break was called, so exit
return 0;
}
编译、链接
gcc test.c -o test -I usr/local/include/ -L usr/local/lib/ -lev
执行
./test
如果提示找不到库。
error while loading shared libraries: libev.so.4: cannot open shared object file: No such file or directory
则需要执行下面语句,设置一下环境变量。
export LD_LIBRARY_PATH=
L
D
L
I
B
R
A
R
Y
P
A
T
H
:
LD_LIBRARY_PATH:
LDLIBRARYPATH:HOME"/test/libev_test/usr/local/lib"
执行结果
如果5.5s内stdin没有输入,则打印timeout,否则打印stdin ready。
PS:libev用于socket通信的例子可以参考下文:
https://www.cnblogs.com/dpf-10/p/5341200.html