1、简介
libevent和libev是高性能事件循环库,它们是解决网络并发问题的针对性方案。开发者通过注册感兴趣的事件,实现并发机制。二者功能类似,但是libev更新、更快、支持功能更多,它支持I/O、时钟等8种时间,响应时间在us至ms级别。
libev官方定义:libev - a high performance full-featured event loop written in C
2、Libev安装
环境ubuntu 12.04
sudo apt-get install libev-dev
直接安装libev4
3、试用
代码为官网实例,监听I/O输入和超时事件。
#include<ev.h>
#include<stdio.h>
// every watcher tupe 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, 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);
ev_run(loop,0);
return 0;
}
编译:假设文件命名为libev.c,编译gcc libev.c -o libev -lev
常见错误:
1、error while loading shared libraries: libev.so.4: cannot open shared object file: No such file or directory
博主瀚海星空 http://abloz.com/2010/11/24/libev-usage-examples.html 对问题做出了解释。
动态库查找顺序和路径:
(1)在编译目标代码时指定该程序的动态库搜索路径(还可以在编译目标代码时指定程序的动态库搜索路径)。这是通过gcc 的参数”-Wl,-rpath,”指定。当指定多个动态库搜索路径时,路径之间用冒号”:”分隔;
(2)通过环境变量LD_LIBRARY_PATH指定动态库搜索路径(多个用:隔开);
(3)在配置文件/etc/ld.so.conf中指定动态库搜索路径;
(4)默认的动态库搜索路径/lib /usr/lib
设置动态库查找路径:
$ export LD_LIBRARY_PATH=/usr/local/lib
然后再次执行即可。
转载于:https://blog.51cto.com/speakingbaicai/1109337