1. 程式人生 > >select與epoll

select與epoll

logs xevent 任務 文件 hash span int 註冊事件 檢查

select的api:

#include <sys/select.h>
#include <sys/time.h>

int select(int maxfdp1,fd_set *readset,fd_set *writeset,fd_set *exceptset,const struct timeval *timeout)
返回值:就緒描述符的數目,超時返回0,出錯返回-1

epoll的api:

#include <sys/epoll.h>
int epoll_create(int size);//創建epoll句柄

int epoll_ctl(int epfd, int
op, int fd, struct epoll_event *event);//註冊事件 int epoll_wait(int epfd, struct epoll_event * events, int maxevents, int timeout);//等待事件發生,返回事件發生的個數

epoll的兩種工作模式:

  LT模式(默認):當epoll_wait檢測到描述符事件發生並將此事件通知應用程序,應用程序可以不立即處理該事件。下次調用epoll_wait時,會再次響應應用程序並通知此事件。

  ET模式:當epoll_wait檢測到描述符事件發生並將此事件通知應用程序,應用程序必須立即處理該事件。如果不處理,下次調用epoll_wait時,不會再次響應應用程序並通知此事件。

  ET模式在很大程度上減少了epoll事件被重復觸發的次數,因此效率要比LT模式高。epoll工作在ET模式的時候,必須使用非阻塞套接口,以避免由於一個文件句柄的阻塞讀/阻塞寫操作把處理多個文件描述符的任務餓死。

select與epoll的區別

1.select實現需要自己不斷在內核態輪詢所有fd集合,epoll只需檢查就緒隊列(epoll事件發生觸發回調函數,回調函數把就緒的fd加入就緒鏈表中)

2.select每次調用都要把fd集合從用戶態往內核態拷貝一次,epoll只要一次拷貝

3.select的fd集合在內核中是數組,poll是鏈表,epoll是hash表或紅黑樹來維護。

select與epoll