内核源码: https://www.nowcoder.com/discuss/26226?type=0&order=0&pos=21&page=1
epoll流程:
首先调用epoll_create建立一个epoll对象,epoll_ctl可以操作上面建立的epoll对象,例如,将刚建立的socket加入到epoll中让其监控,或者把 epoll正在监控的某个socket句柄移出epoll,不再监控它等等。epoll_wait在调用时,在给定的timeout时间内,当在监控的所有句柄中有事件发生时,就返回用户态的进程。
当一个进程调用epoll_create方法时,linux内核会创建一个eventpoll结构体,每个epoll对象都有一个独立的eventpoll结构体,这个结构体会在内核空间中创造独立的内存,用于存储使用epoll_ctl方法向epoll对象中添加进来的事件。这样,重复的事件就可以通过红黑树高效地识别出来。
在epoll中,对于每一个事件都会建立一个epitem结构体。epoll还维护了一个双链表,用于存储发生的事件。当epoll_wait调用时,仅仅观察这个链表中有没有数据即eptime项即可。有数据就返回,没有数据就sleep,等到timeout时间到后即使链表没数据也返回。
准备就绪链表的维护:
当我们执行epoll_ctl时,除了把socket放到epoll文件系统里epoll对象对应的红黑树上之外,还会给内核中断处理程序注册一个回调函数,告诉内核,如果这个句柄的中断到了,就把它放到准备就绪list链表里。
执行epoll_create时,创建了红黑树和就绪链表(eventpoll结构体成员),执行epoll_ctl时,如果增加socket句柄,则检查在红黑树中是否存在,存在立即返回,不存在则添加到树干上,然后向内核注册回调函数,用于当中断事件来临时向准备就绪链表中插入数据。执行epoll_wait时立刻返回准备就绪链表里的数据即可。
1. int epoll_create(int size);
创建一个epoll的句柄。自从linux2.6.8之后,size参数是被忽略的。需要注意的是,当创建好epoll句柄后,它就是会占用一个fd值,在linux下如果查看/proc/进程id/fd/,是能够看到这个fd的,所以在使用完epoll后,必须调用close()关闭,否则可能导致fd被耗尽。
2. int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
epoll的事件注册函数
第一个参数是epoll_create()的返回值。
第二个参数表示动作,用三个宏来表示:
EPOLL_CTL_ADD:注册新的fd到epfd中;
EPOLL_CTL_MOD:修改已经注册的fd的监听事件;
EPOLL_CTL_DEL:从epfd中删除一个fd;
第三个参数是需要监听的fd。
第四个参数是告诉内核需要监听什么事,event.data.fd就是第三个参数fd,event.events是该fd上需要监听的事件类型,struct epoll_event结构如下
//保存触发事件的某个文件描述符相关的数据(与具体使用方式有关) typedef union epoll_data { void *ptr; int fd;//需要监听的文件描述符 __uint32_t u32; __uint64_t u64; } epoll_data_t; //感兴趣的事件和被触发的事件 struct epoll_event { __uint32_t events; /* Epoll events *///需要监听的文件描述符的事件类型 epoll_data_t data; /* User data variable */ };
events可以是以下几个宏的集合:
EPOLLIN :表示对应的文件描述符可以读(包括对端SOCKET正常关闭);
EPOLLOUT:表示对应的文件描述符可以写;
EPOLLPRI:表示对应的文件描述符有紧急的数据可读(这里应该表示有带外数据到来);
EPOLLERR:表示对应的文件描述符发生错误;
EPOLLHUP:表示对应的文件描述符被挂断;
EPOLLET: 将EPOLL设为边缘触发(Edge Triggered)模式,这是相对于水平触发(Level Triggered)来说的。
EPOLLONESHOT:只监听一次事件,当监听完这次事件之后,如果还需要继续监听这个socket的话,需要再次把这个socket加入到EPOLL队列里
3. int epoll_wait(int epfd, struct epoll_event * events, int maxevents, int timeout);
收集在epoll监控的事件中已经发生的事件。参数events是分配好的epoll_event结构体数组,epoll将会把发生的事件赋值到events数组中(events不可以是空指针,内核只负责把数据复制到这个events数组中,不会去帮助我们在用户态中分配内存)。maxevents告之内核这个events有多大,这个 maxevents的值不能大于创建epoll_create()时的size,参数timeout是超时时间(毫秒,0会立即返回,-1是阻塞调用)。如果函数调用成功,返回对应I/O上已准备好的文件描述符数目,如返回0表示已超时。
epoll工作原理:
epoll同样只告知那些就绪的文件描述符,而且当我们调用epoll_wait()获得就绪文件描述符时,返回的不是实际的描述符,而是一个代表就绪描述符数量的值,你只需要去epoll指定的一个数组中依次取得相应数量的文件描述符即可,这里也使用了内存映射(mmap)技术,这样便彻底省掉了这些文件描述符在系统调用时复制的开销。(我的理解:内核调用epoll_wait时,把就绪的fd及事件赋值到events数组中,用户在用户态中可以直接使用events数组,所以这其中用到mmap技术)
另一个本质的改进在于epoll采用基于事件的就绪通知方式(每个socket上注册一个回调函数)。在select/poll中,进程只有在调用一定的方法后,内核才对所有监视的文件描述符进行扫描,而epoll事先通过epoll_ctl()来注册一个文件描述符,一旦基于某个文件描述符就绪时,内核会采用类似callback的回调机制,迅速激活这个文件描述符,当进程调用epoll_wait()时便得到通知。
Epoll的2种工作方式-水平触发(LT)和边缘触发(ET):
epoll对文件描述符的操作有两种模式:LT(level trigger)和ET(edge trigger)。LT模式是默认模式
ET模式在很大程度上减少了epoll事件被重复触发的次数,因此效率要比LT模式高。epoll工作在ET模式的时候,必须使用非阻塞套接口,以避免由于一个文件句柄的阻塞读/阻塞写操作把处理多个文件描述符的任务饿死(在while循环中调用read、write、accept,若是阻塞套接字,当资源不够时,进程会被阻塞,则其他准备就绪的文件描述符得不到处理,如果是非阻塞套接字,当资源不够时,上述系统调用返回-1,同时将errno设置为EAGAIN)
LT模式下开发基于epoll的应用要简单些,不太容易出错。而在ET模式下事件发生时,如果没有彻底地将缓冲区数据处理完,则会导致缓冲区中的用户请求得不到响应。
epoll相比select/poll的优点:
1.epoll支持一个进程打开大数目的socket描述符(FD),select中一个进程打开的fd数目是有限制的,传统的apache方案是选择多进程来解决,但是创建进程是有代价的,而且进程间数据同步远比不上线程间同步的高效
2.epoll的IO效率不随FD数目增加而线性下降,select/poll每次调用都会线性扫描所有的集合,导致效率呈线性下降,而epoll在每个fd上面有callback函数,当监听的事件发生时,callback函数会自动将数据添加到就绪链表中(基于事件的就绪通知方式)。
3.epoll使用mmap加速内核与用户空间的消息传递,通过内核与用户空间mmap同一块内存实现(我的理解:epoll_wait中events参数,在内核态下赋值,用户态可以直接使用)
4.每次调用select,都需要把fd集合从用户态拷贝到内核态,而每次调用epoll_ctl只是在往内核的数据结构里塞入新的socket句柄
epoll的使用方法:
首先通过epoll_create(int maxfds)来创建一个epoll的句柄。这个函数会返回一个新的epoll句柄,之后的所有操作将通过这个句柄来进行操作。在用完之后,记得用close()来关闭这个创建出来的epoll句柄,因为epoll对象占用一个fd值。
之后在你的网络主循环里面,每一帧的调用epoll_wait(int epfd, epoll_event events, int max events, int timeout)来查询所有的网络接口,看哪一个可以读,哪一个可以写了。基本的语法为:nfds = epoll_wait(kdpfd, events, maxevents, -1);
其中kdpfd为用epoll_create创建之后的句柄,events是一个epoll_event*的指针,当epoll_wait这个函数操作成功之后,epoll_events里面将储存所有的读写事件。max_events是当前需要监听的所有socket句柄数。最后一个timeout是 epoll_wait的超时,为0的时候表示马上返回,为-1的时候表示一直等下去,直到有事件返回,为任意正整数的时候表示等这么长的时间,如果一直没有事件,则返回。一般如果网络主循环是单独的线程的话,可以用-1来等(即阻塞调用epoll_wait),这样可以保证一些效率,如果是和主逻辑在同一个线程的话,则可以用0来保证主循环的效率。epoll_wait返回之后应该是一个循环,遍历所有的事件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
for( ; ; ) { nfds = epoll_wait(epfd,events,20,500); for(i=0;i<nfds;++i) { if(events[i].data.fd==listenfd) //有新的连接 { connfd = accept(listenfd,(sockaddr *)&clientaddr, &clilen); //accept这个连接 ev.data.fd=connfd; ev.events=EPOLLIN|EPOLLET; epoll_ctl(epfd,EPOLL_CTL_ADD,connfd,&ev); //将新的fd添加到epoll的监听队列中 } else if( events[i].events&EPOLLIN ) //接收到数据,读socket { n = read(sockfd, line, MAXLINE)) < 0 //读 ev.data.ptr = md; //md为自定义类型,添加数据 ev.events=EPOLLOUT|EPOLLET; epoll_ctl(epfd,EPOLL_CTL_MOD,sockfd,&ev);//修改标识符,等待下一个循环时发送数据,异步处理的精髓 } else if(events[i].events&EPOLLOUT) //有数据待发送,写socket { struct myepoll_data* md = (myepoll_data*)events[i].data.ptr; //取数据 sockfd = md->fd; send( sockfd, md->ptr, strlen((char*)md->ptr), 0 ); //发送数据 ev.data.fd=sockfd; ev.events=EPOLLIN|EPOLLET; epoll_ctl(epfd,EPOLL_CTL_MOD,sockfd,&ev); //修改标识符,等待下一个循环时接收数据 } else { //其他的处理 } } }
/* 171 * This structure is stored inside the "private_data" member of the file 172 * structure and represents the main data structure for the eventpoll 173 * interface. 174 */ 175struct eventpoll { 176 /* Protect the access to this structure */ 177 spinlock_t lock; 178 179 /* 180 * This mutex is used to ensure that files are not removed 181 * while epoll is using them. This is held during the event 182 * collection loop, the file cleanup path, the epoll file exit 183 * code and the ctl operations. 184 */ 185 struct mutex mtx; 186 187 /* Wait queue used by sys_epoll_wait() */ 188 wait_queue_head_t wq; 189 190 /* Wait queue used by file->poll() */ 191 wait_queue_head_t poll_wait; 192 193 /* List of ready file descriptors */ 194 struct list_head rdllist; 195 196 /* RB tree root used to store monitored fd structs */ 197 struct rb_root rbr;//红黑树根节点,这棵树存储着所有添加到epoll中的事件,也就是这个epoll监控的事件 198 199 /* 200 * This is a single linked list that chains all the "struct epitem" that 201 * happened while transferring ready events to userspace w/out 202 * holding ->lock. 203 */ 204 struct epitem *ovflist; 205 206 /* wakeup_source used when ep_scan_ready_list is running */ 207 struct wakeup_source *ws; 208 209 /* The user that created the eventpoll descriptor */ 210 struct user_struct *user; 211 212 struct file *file; 213 214 /* used to optimize loop detection check */ 215 int visited; 216 struct list_head visited_list_link;//双向链表中保存着将要通过epoll_wait返回给用户的、满足条件的事件 217}; /* 130 * Each file descriptor added to the eventpoll interface will 131 * have an entry of this type linked to the "rbr" RB tree. 132 * Avoid increasing the size of this struct, there can be many thousands 133 * of these on a server and we do not want this to take another cache line. 134 */ 135struct epitem { 136 /* RB tree node used to link this structure to the eventpoll RB tree */ 137 struct rb_node rbn; 138 139 /* List header used to link this structure to the eventpoll ready list */ 140 struct list_head rdllink; 141 142 /* 143 * Works together "struct eventpoll"->ovflist in keeping the 144 * single linked chain of items. 145 */ 146 struct epitem *next; 147 148 /* The file descriptor information this item refers to */ 149 struct epoll_filefd ffd; 150 151 /* Number of active wait queue attached to poll operations */ 152 int nwait; 153 154 /* List containing poll wait queues */ 155 struct list_head pwqlist; 156 157 /* The "container" of this item */ 158 struct eventpoll *ep; 159 160 /* List header used to link this item to the "struct file" items list */ 161 struct list_head fllink; 162 163 /* wakeup_source used when EPOLLWAKEUP is set */ 164 struct wakeup_source __rcu *ws; 165 166 /* The structure that describe the interested events and the source fd */ 167 struct epoll_event event; 168};