epoll.c
//linux下效率最高的多路转接与复用
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/epoll.h>
#define SIZE 4096
int main(void)
{
int ret,fifoFd;
char buf[SIZE+1];
//create fifo
if(access("/tmp/myfifo",F_OK)!=0)//判断文件是否存在
{
if(mkfifo("/tmp/myfifo",0644)==-1)//不存在,创建
{
perror("create fifo");
return 1;
}
}
//open fifo
fifoFd=open("/tmp/myfifo",O_RDONLY);//打开fifo文件
if(fifoFd==-1)
{
perror("open fifo");
return 2;
}
printf("open fifo success.\n");
//创建epoll机制
int epfd;
//内核2.6.8之后int epoll_create1(int flags)替换int epoll_create(int size);
//返回epoll机制的句柄 占用一个文件描述
//epfd=epoll_create1(0);
epfd=epoll_create1(EPOLL_CLOEXEC);//执行execl后自动关闭epfd
if(epfd==-1)
{
perror("epoll create");
return 3;
}
//设置epoll
struct epoll_event ev;
ev.events=EPOLLIN;
ev.data.fd=STDIN_FILENO;
ret=epoll_ctl(epfd,EPOLL_CTL_ADD,STDIN_FILENO,&ev);//添加监听,STDIN_FILENO监听的文件描述符,ev是事件发生时的数据
if(ret==-1)
{
perror("add stdin event");
return 4;
}
//
ev.events=EPOLLIN|EPOLLHUP;
ev.data.fd=fifoFd;
ret=epoll_ctl(epfd,EPOLL_CTL_ADD,fifoFd,&ev);
if(ret==-1)
{
perror("add fifo event");
return 5;
}
//进入事件等待
struct epoll_event revents;
while(1)
{
ret=epoll_wait(epfd,&revents,1,-1);//监听,-1表示阻塞
printf("epoll wait ret:%d\n",ret);
if(ret<=0) continue;
//移除挂断的描述符
if(revents.data.fd==fifoFd && (revents.events & EPOLLHUP))
{
ev.data.fd=fifoFd;
ev.events=EPOLLIN|EPOLLHUP;
if(epoll_ctl(epfd,EPOLL_CTL_DEL,fifoFd,&ev)==-1)
{
perror("epoll_ctl del");
}
close(fifoFd);
printf("移除写端关闭的fifo\n");
continue;
}
ret=read(revents.data.fd,buf,SIZE);
if(ret==0||ret==-1)
{
perror("read");
break;
}
buf[ret]='\0';
printf("%d>>%s\n",revents.data.fd,buf);
}
close(epfd);
close(fifoFd);
return 0;
}
writeFifo.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define SIZE 4096
int main(void)
{
int ret,fifoFd;
char buf[SIZE+1];
//create fifo
if(access("/tmp/myfifo",F_OK)!=0)
{
if(mkfifo("/tmp/myfifo",0644)==-1)
{
perror("create fifo");
return 1;
}
}
//open fifo
fifoFd=open("/tmp/myfifo",O_WRONLY);
if(fifoFd==-1)
{
perror("open fifo");
return 2;
}
printf("open fifo success.\n");
while(1)
{
fgets(buf,SIZE,stdin);
write(fifoFd,buf,strlen(buf));
}
close(fifoFd);
return 0;
}
编译 make writeFifo && make epoll
同时打开两个终端分别执行两个程序,在writeFifo里输入,在epoll里查看效果;