安装

开源。精简。跨平台(Windows、Linux、maxos、unix)。专注于网络通信。
源码包安装: 参考 README、readme
./configure 检查安装环境 生成 makefile
make 生成 .o 和 可执行文件
sudo make install 将必要的资源cp置系统指定目录。
进入 sample 目录,运行demo验证库安装使用情况。
编译使用库的 .c 时,需要加 -levent 选项。
库名 libevent.so --> /usr/local/lib 查看的到。
特性:
基于“事件”异步通信模型。--- 回调。

libevent框架

libevent框架_释放资源

创建事件event

libevent框架_事件循环_02

添加、摘除和销毁事件

libevent框架_释放资源_03

使用fifo进行读写

读:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <event2/event.h>

// 对操作处理函数
void read_cb(evutil_socket_t fd, short what, void *arg)
{
// 读管道
char buf[1024] = {0};

int len = read(fd, buf, sizeof(buf));

printf("read event: %s \n", what & EV_READ ? "Yes" : "No");
printf("data len = %d, buf = %s\n", len, buf);

sleep(1);
}


// 读管道
int main(int argc, const char* argv[])
{
unlink("myfifo");

//创建有名管道
mkfifo("myfifo", 0664);

// open file
//int fd = open("myfifo", O_RDONLY | O_NONBLOCK);
int fd = open("myfifo", O_RDONLY);
if(fd == -1)
{
perror("open error");
exit(1);
}

// 创建个event_base
struct event_base* base = NULL;
base = event_base_new();

// 创建事件
struct event* ev = NULL;
ev = event_new(base, fd, EV_READ | EV_PERSIST, read_cb, NULL);

// 添加事件
event_add(ev, NULL);

// 事件循环
event_base_dispatch(base); // while(1) { epoll();}

// 释放资源
event_free(ev);
event_base_free(base);
close(fd);

return 0;
}

写:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <event2/event.h>

// 对操作处理函数
void write_cb(evutil_socket_t fd, short what, void *arg)
{
// write管道
char buf[1024] = {0};

static int num = 0;
sprintf(buf, "hello,world-%d\n", num++);
write(fd, buf, strlen(buf)+1);

sleep(1);
}


// 写管道
int main(int argc, const char* argv[])
{
// open file
//int fd = open("myfifo", O_WRONLY | O_NONBLOCK);
int fd = open("myfifo", O_WRONLY);
if(fd == -1)
{
perror("open error");
exit(1);
}

// 写管道
struct event_base* base = NULL;
base = event_base_new();

// 创建事件
struct event* ev = NULL;
// 检测的写缓冲区是否有空间写
//ev = event_new(base, fd, EV_WRITE , write_cb, NULL);
ev = event_new(base, fd, EV_WRITE | EV_PERSIST, write_cb, NULL);

// 添加事件
event_add(ev, NULL);

// 事件循环
event_base_dispatch(base);

// 释放资源
event_free(ev);
event_base_free(base);
close(fd);

return 0;
}

事件的未决和非未决

libevent框架_#include_04

bufferevent

libevent框架_#include_05
libevent框架_释放资源_06
libevent框架_事件循环_07
libevent框架_释放资源_08
libevent框架_#include_09
libevent框架_释放资源_10
libevent框架_#include_11

主要是给自己看的,所以肯定会出现很多错误哈哈哈哈哈