多路IO轉接伺服器實現方法三 epoll 函式

2021-10-10 11:56:03 字數 1509 閱讀 8103

epoll是linux下多路復用介面select/poll的增強版本。

它能顯著提高程式在大量併發連線中只有少量活躍的情況下的系統cpu利用率,因為它會復用檔案描述符集合來傳遞結果而不用每次等待時間之前都必須重新準備要被監聽的檔案描述符集合

獲取事件的時候,它無須遍歷整個被監聽的檔案描述符集,只要遍歷那些被核心io事件非同步喚醒而加入ready佇列的描述符集合就行了

目前epoll是linux大規模併發網路程式中的熱門首選模型

除了提供select/poll那種io事件的電平觸發外,還提供了邊沿觸發,這使得使用者空間程式有可能暫存io狀態,減少epoll_wait/epoll_pwait的呼叫,提高應用程式效率

函式原型

int epoll_create(int size);

函式原型

int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);

兩個結構體

struct epoll_event

struct

union epoll_dataepoll_data_t;

函式原型

int epoll_wait(int epfd,struct epoll_event *events,int maxevents, int timeout);

返回值成功返回有多少滿足條件的檔案描述符。

超時時間到時返回0,出錯返回-1.

#include

#include

#include

#include

#include

#include

#include

#include

#include

#define ip "127.0.0.1"

#define port 8888

intmain()

//3、監聽,設定最大連線數

listen

(sfd,

128)

;//開始使用epoll幫忙監聽

while(1

)//將sfd檔案描述符掛到這顆紅黑樹上

struct epoll_event inevent;

inevent.events = epollin;

inevent.data.fd = sfd;

epoll_ctl

(epfd,epoll_ctl_add,sfd,

&inevent)

;while(1

)else

else

if(len >0)

write

(sockfd,rwbuf,len);}

}}}}

close

(sfd)

;return0;

}

多路IO轉接伺服器實現方法一 select 函式

採用多程序與多執行緒的方法來實現併發伺服器時,監聽的工作由server應用程式自身通過accept函式不斷去監聽。當客戶端連線較多時,這種方法會大大降低程式執行效率,消耗cpu資源 cpu需要在不同進 執行緒中切換執行 多程序與多執行緒實現併發伺服器方法可以參考以下兩篇文章 因為以上兩種方法的侷限性...

I O多路轉接 epoll伺服器

在前面的兩篇部落格中,我們介紹了最早期的select和改進版的poll 但是,他兩都沒有改進的就是,想要快速知道事件就緒並沒有得到改進,兩個全部是遍歷陣列,我們都知道它的時間複雜度就是o n 效率不是很高,時間複雜度達到o 1 才是高效的 epoll是linux特有的i o復用函式,它在實現和使用上...

多路IO轉接伺服器實現方法二 poll 函式

相較於多路io轉接伺服器實現方法一 select 函式,使用poll 函式的優點有 檔案描述符的上限可以突破1024 select 函式監聽集合與返回的滿足監聽條件的集合為乙個集合,而poll函式將監聽集合與符合監聽條件的集合實現了分離 搜尋滿足條件的檔案描述符的範圍縮小了 但,poll函式不能實現...