1.概述与安装
2.IO事件
3.信号事件
1.概述与安装
备注:安装包:deb包 二进制文件:
源码: tar.gz
#1.安装二进制文件
apt-get download libevent-dev
apt-get install libevent-dev
#验证
ls /usr/include/event.h
#查看与解释
ls #查看文件内容 dpkg 解压到deb中
dpkg -x libevent-dev_2.0.21-stable-2ubuntu0.16.04.1_amd64.deb deb
ls deb
include lib share #3个 event2这个目录里
#cd share/examples
#hello-world.c 服务器 event-test.c 管道 signal-test.c 信号事件 time-test.c 定时器事件
#2.源码
wget https://github.com/libevent/libevent
两个结构体+常用接口
2.IO事件
管道读代码1-fiforead.c
创建事件集合:struct event ev;
监听事件:event_dispatch();
操作的是全局变量:current_base
#include <stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<fcntl.h>
#include<event.h>
#include<unistd.h>
/*
回调函数 读取数据
*/
void fifo_read(evutil_socket_t fd,short events,void *arg)
{
char buf[32]={0};
int ret=read(fd,buf,sizeof(buf));
if(-1==ret)
{
perror("read");
exit(1);
}
printf("从管道读取%s\n",buf);
}
int mainread()
{
//1.创建管道
int ret= mkfifo("fifo.tmp",00700);#管道的名字,权限
if(-1==ret)
{
perror("mkfifo");
exit(1);
}
//2.打开管道
int fd=open("fifo.tmp",O_RDONLY);
if(-1==ret)
{
perror("mkfifo");
exit(1);
}
//3.创建事件
struct event ev;
//初始化事件集合 #Event.c中 创建 struct event_base 对象; 赋值给全局变量 current_base
event_init();
//4初始化事件 (把ev和fd绑定) include\event2 事件类型:EV_READ 文件 #event_compat.h
//事件 关联的文件描述符 事件类型 回调函数 回调函数参数
event_set(&ev,fd,EV_READ | EV_PERSIST,fifo_read,NULL);
event_add(&ev,NULL);
//开始监听
event_dispatch();
return 0;
}
添加参数 EV_PERSIST
管道写代码:1-fifowrite.c
#include <stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<fcntl.h>
#include<event.h>
#include<unistd.h>
/*
主函数写数据
*/
void main_write()
{
//1.创建管道 默认为阻塞
int ret=mkfifo("fifo.tmp",00400|00200);
if(-1==ret)
{
perror("mkfifo");
exit(1);
}
//2.打开管道
int fd=open("fifo.tmp",O_WRONLY);
if(-1==fd)
{
perror("mkfifo");
exit(1);
}
char buf[32]={0};
while(1)
{
scanf("%s",buf);
ret=write(fd,buf,strlen(buf));
if(-1==ret)
{
perror("write");
exit(1);
}
if(!strcmp(buf,"bye"))
{
break;
}
memset(buf,0,sizeof(buf));
}
}
3.信号事件
gcc 3-signal.c -o 3-signal -levent 编译
./3-signal 运行
创建事件集合:struct event ev; struct event_base *base=event_base_new();
监听事件:event_base_dispath();
操作的是自定义变量:base
3-signal.c
#include <stdio.h>
#include<signal.h>
#include<event.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<fcntl.h>
#include<event.h>
#include<unistd.h>
/*
回调函数 读取数据
*/
void signal_handler(evutil_socket_t fd,short events,void *arg)
{
struct event *ev=(struct event *)arg;
printf("收到信号 %d\n",fd);
signal_count++;
if(signal_count>=2)
{
//把事件从集合中删除
event_del(ev);
}
}
int main()
{
//1.创建事件集合 函数查找 Event.c event_set()把事件加入到 current_base中 event_assign()把事件加入到指定的事件中
struct event_base *base =event_base_new();
//2.创建事件
struct event ev;
//3.事件与信号绑定
event_assign(&ev,base,SIGINT,EV_SIGNAL|EV_PERSIST,signal_handler,&ev);
//事件添加到集合中
event_add(&ev,NULL);
//监听集合
event_dispatch();
//释放集合
event_base_free(base);
return 0;
}