CentOS 7 使用异步网络框架Libevent

CentOS 7 安装Libevent库

libevent github地址:https://github.com/libevent/libevent

步骤1:首先,你需要下载libevent的源代码。你可以从github或者源代码官方网站下载。并上传至/usr/local/source_code/   

步骤2:下载完成后,需要将源代码解压,可以使用以下命令:

[root@localhost source_code]# tar -zxvf libevent-2.1.12-stable.tar.gz

 步骤3:解压后,切换到源代码目录: 

[root@localhost source_code]# cd libevent-2.1.12-stable

 步骤4:生成cJSON动态/静态库,执行如下指令: 

[root@localhost libevent-2.1.12-stable]# ./configure
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /usr/bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking whether make supports nested variables... (cached) yes
checking whether make supports the include directive... yes (GNU
******
[root@localhost libevent-2.1.12-stable]# make
  GEN      test/rpcgen-attempted
  GEN      include/event2/event-config.h
make  all-am
make[1]: 进入目录“/usr/local/source_code/libevent-2.1.12-stable”
  CC       sample/dns-example.o
  CC       buffer.lo
  CC       bufferevent.lo
  CC       bufferevent_filter.lo
******
[root@localhost libevent-2.1.12-stable]# sudo make install
make  install-am
make[1]: 进入目录“/usr/local/source_code/libevent-2.1.12-stable”
make[2]: 进入目录“/usr/local/source_code/libevent-2.1.12-stable”
 /usr/bin/mkdir -p '/usr/local/bin'
 /usr/bin/install -c event_rpcgen.py '/usr/local/bin'
 /usr/bin/mkdir -p '/usr/local/lib'
****

 

遇到的问题及解决办法

编译执行./test_libevent,提示如下截图错误信息:

产生原因:在运行时,程序无法找到libevent-2.1.so.7这个动态库,因为该动态库在默认安装时,存放的路径在/usr/local/lib下,不在系统的默认查找路径内。

解决办法:

[root@localhost libevent_demo]# cat /etc/ld.so.conf
include ld.so.conf.d/*.conf
/usr/local/openssl/lib
/usr/local/openssl/lib
[root@localhost libevent_demo]# echo "/usr/local/lib" >> /etc/ld.so.conf
[root@localhost libevent_demo]# sudo ldconfig

 Libevent 之Hello World

在/usr/local/source_code 新增 libevent_demo目录并新增 test_libevent.cpp文件,文件内容如下:

#include <event2/event.h>
#include <iostream>
#include <string>
void timer_cb(evutil_socket_t fd, short what, void *arg)
{
    auto str = static_cast<std::string *>(arg);
    std::cout << *str << std::endl;
}
int main()
{
    std::string str = "Hello, World!";
    auto *base = event_base_new();
    struct timeval five_seconds = {1, 0};
    auto *ev = event_new(base, -1, EV_TIMEOUT, timer_cb, (void *)&str);
    event_add(ev, &five_seconds);
    event_base_dispatch(base);
    event_free(ev);
    event_base_free(base);
    return 0;
}

编译源码并执行:

[root@localhost libevent_demo]# g++ test_libevent.cpp -o test_libevent -levent
[root@localhost libevent_demo]# ./test_libevent
Hello, World!

Libevent 参考资料:

libevent GitHub地址:https://github.com/libevent/libevent

libevent 编程指南: https://senlinzhan.github.io/2017/08/12/libevent/ 

libevent 深入浅出:https://aceld.gitbooks.io/libevent/content/ 

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码

)">
< <上一篇
下一篇>>