一. epoll的含义的定义
epoll是Linux下多路复用IO接口select/poll的增强版本,它能显著提高程序在大量并发连接中只有少量活跃的情况下的系统CPU利用率,因为它会复用文件描述符集合来传递结果而不用迫使开发者每次等待事件之前都必须重新准备要被侦听的文件描述符集合,另一点原因就是获取事件的时候,它无须遍历整个被侦听的描述符集,只要遍历那些被内核IO事件异步唤醒而加入Ready队列的描述符集合就行了。
一、基础API
1.1 创建一个epoll句柄,参数size用来告诉内核监听的文件描述符的个数,跟内存大小有关。
#include <sys/epoll.h>
int epoll_create(int size) size:监听数目
1.2 控制某个epoll监控文件描述符上的事件:注册、修改、删除
#include <sys/epoll.h>
int epoll_ctl(int epfd,int op,int fd,struct epoll_event *event)
epfd:为epoll_create返回的句柄
op:表示动作,用三个宏来表示;
EPOLL_CTL_ADD (注册新的fd到epfd),
EPOLL_CTL_MOD (修改已经注册的fd的监听事件),
EPOLL_CTL_DEL (从epfd删除一个fd);
event:高速内核需要监听的事件
struct epoll_event{
__uint32_t events; /*Epoll events*/
epoll_data_t data; /*User data variable*/
};
events:取值为EPOLLIN/EPOLLOUT/EPOLLRDHUP 读/写/异常
typedef union epoll_data{
void *ptr;
int fd;
uint32_t u32;
uint64_t u64;
}epoll_data_t ;
1.3 等待所监控文件描述上有事件的产生,类似于select()调用。
#include <sys/epoll.h>
int epoll_wait(int epfd,struct epoll_event *events,int maxevents,int timeout)
events:用来存内核得到事件的集合
maxevents:告知内核这个events有多大,这个maxevents的值不能大于创建epoll_create()时的size
timeout:是超时时间
-1:阻塞
0:立即返回,非阻塞
>0:指定毫秒
返回值:成功返回有多少文件描述符就绪,时间到返回0,出错返回-1.