libevent项目分析(一) -- 准备阶段发布时间:2022/5/31 13:16:38
项目的简介
我理解libevent是一个轻量级的,跨平台+高效的(C语言实现)事件驱动库,类似于ACE项目中的ACE_Reactor,它实现了网络通讯套接口I/O事件,定时器事件,信号事件的监听和事件处理函数回调机制。从项目主页可以了解到libevent已经支持 /dev/poll, kqueue(2), event ports, POSIX select(2), Windows select(), poll(2), and epoll(4)方式的事件监测和驱动机制
项目主页:http://libevent.org/
维基百科:http://zh.wikipedia.org/wiki/Libevent
参考资料:http://blog.csdn.net/sparkliang/article/details/4957667
PS:在分析开源项目代码之前,需首先了解该项目的特性,应用场景和价值,这些信息一方面可以从项目的主页获取,另一方面可以通过搜索引擎从技术论坛,博客等方面获取。最好选择和自己工作/兴趣比较相关的项目,这样有利于分析的深入和坚持,并及时体现收益。
下载源代码
从项目主页可以很方便的下载当前版本的源码,我下载的版本是libevent-2.0.17-stable.tar.gz
代码量分析
通过Wine运行SourceCounter工具对该项目进行代码量统计,可以看到该项目代码量大概5W多行,且代码工程结构简单,比较适合像我这样对开源项目代码分析经验不足的人
PS:在开始分析项目源码之前,分析该项目的代码量可以大致评估该项目的难度和分析计划,分析工程结构可以大致评估该项目的重点部分,以免一开始就满腔热血地栽在一个深坑里(比较复杂的开源项目),而后面又不了了之
编译和安装
在将源码包在本地解压后即可以编译和安装。这里和其他开源项目差不多,没有什么特别的,只是为了方便后面通过调试的手段来分析源码,编译的时候最好编译成debug模式,如下
#./configure --enable-debug-mode --enable-static --enable-thread-support
#make
#make install
安装完成后,libevent库的头文件会安装在/usr/local/include目录下,而库文件会安装在/usr/local/lib目录下,故需确保/usr/local/lib在LD_LIBRARY_PATH变量包含的路径中
PS:卸载的方法
#make uninstall
#make clean
编写测试应用代码
该项目源码包中的sample目录中其实已经有些例子,但我还是情愿参考样例自己写一个,好久没Coding了 :)
mytimer.c : 实现一个定时器事件处理函数,并通过libevent的事件驱动机制定时调用
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
static void handle_timer(evutil_socket_t fd, short event, void* arg)
{
printf("handle_timer function is called \n");
fflush(stdout);
}
int main(int argc, char** argv)
{
/* Initalize the event library */
struct event_base* base = event_base_new();
if (NULL == base)
{
return -1;
}
/* Initalize one timeout event */
struct event timeout = {0};
event_assign(&timeout, base, -1, EV_PERSIST, handle_timer, (void*)&timeout);
/* Register the event */
struct timeval tv;
evutil_timerclear(&tv);
tv.tv_sec = 2;
event_add(&timeout, &tv);
/*event dispatch*/
event_base_dispatch(base);
event_base_free(base);
return 0;
}
编译 : gcc -g -I/usr/local/include -o mytimer mytimer.c -L/usr/local/lib -levent
运行 : $ ./mytimer
handle_timer function is called
handle_timer function is called
handle_timer function is called
^C
通过例程调试libevent
通过gdb去调试mytimer时发现其链接的是libevent的动态库,且无法在libevent库的函数上设置断点 :(
安装glibc的静态库:# yum install glibc-static libstdc++-static
静态编译命令:gcc -g -I/usr/local/include -o mytimer mytimer.c -L/usr/local/lib -static -levent -lc -lrt
这样就可以通过gdb调试例程时,在libevent库的函数上设置断点
 |