阻塞IO和进程的多路复用。
相比select的优点:
epoll();
1.高效
2.监控无上限
epoll的使用:
epoll_create/epoll_creatl(创建监听池)
epoll_ctl(添加监听事件)
epoll_wait(等待事件发生)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/epoll.h>
int main()
{
int fd1,fd2;
int efd;
struct epoll_event event;
struct epoll_event *events;
char c;
//创建fifo
mkfifo("/tmp/fifo1",0666);
mkfifo("/tmp/fifo2",0666);
fd1 = open("/tmp/fifo1",O_RDONLY);
fd2 = open("/tmp/fifo2",O_RDONLY);
//创建监听池
efd = epoll_create1(0);
//构造监听事件,加入监听池
event.events = EPOLLIN|EPOLLET;
event.data.fd = fd1;
epoll_ctl(efd,EPOLL_CTL_ADD,fd1,&event);
event.events = EPOLLIN|EPOLLET;
event.data.fd = fd2;
epoll_ctl(efd,EPOLL_CTL_ADD,fd2,&event);
int n = 0;
events = calloc(100,sizeof(event));
n = epoll_wait(efd,events,100,-1);
int i = 0;
for(i = 0;i<n;i++)
{
if(events[i].events&EPOLLIN)
{
read(events[i].data.fd,&c,1);
printf("file %d can be read\n",events[i].data.fd);
}
if(events[i].events&EPOLLOUT)
{
//处理
}
if(events[i].events&EPOLLERR)
{
//处理
}
}
free(events);
close(fd1);
close(fd2);
}
测试1:ew1.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/epoll.h>
int main()
{
int fd;
char c='c';
fd = open("/tmp/fifo1",O_WRONLY);
write(fd,&c,1);
close(fd);
return 0;
}
测试1:ew2.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/epoll.h>
int main()
{
int fd;
char c='c';
fd = open("/tmp/fifo2",O_WRONLY);
write(fd,&c,1);
close(fd);
return 0;
}
运行epoll 程序进入阻塞状态,然后运行ew1,ew2
打印并退出阻塞。