Linux網路程式設計 poll函式

2021-10-07 20:27:49 字數 1537 閱讀 9262

作用:

監視並等待多個檔案描述符的屬性變化。

函式原型:

int poll(struct pollfd *fds, nfds_t nfds, int timeout);
函式引數意義:

fds:指向乙個結構體陣列的第0個元素的指標,每個陣列元素都是乙個struct pollfd結構,用於指定測試某個給定的fd的條件。

struct pollfd;
nfds:用來指定第乙個引數陣列元素個數

timeout: 指定等待的毫秒數,無論 i/o 是否準備好,poll() 都會返回。

關於struct pollfd結構體的一些說明。

fd:每乙個 pollfd 結構體指定了乙個被監視的檔案描述符,可以傳遞多個結構體,指示 poll() 監視多個檔案描述符。

events:指定監測fd的事件(輸入、輸出、錯誤),每乙個事件有多個取值,如下:

revents:revents 域是檔案描述符的操作結果事件,核心在呼叫返回時設定這個域。events 域中請求的任何事件都可能在 revents 域中返回。

注意:每個結構體的 events 域是由使用者來設定,告訴核心我們關注的是什麼,而 revents 域是返回時核心設定的,以說明對該描述符發生了什麼事件。

例子:

#include #include #include #include #include #include #include #include #include #define serv_port 8989

int main(int argc, const char* ar**)

allfd[0].fd = lfd;

allfd[0].events = pollin;

while(1)

// 判斷是否有連線請求

if(allfd[0].revents & pollin)

}// 更新最後乙個元素的下標

max_index = max_index < i ? i : max_index;

}// 遍歷陣列

for(i=1; i<=max_index; ++i)

if(allfd[i].revents & pollin)

;int len = recv(fd, buf, sizeof(buf), 0);

if(len == -1)

else if(len == 0)

else

printf("buf toupper: %s\n", buf);

send(fd, buf, strlen(buf)+1, 0);}}

}}close(lfd);

return 0;

}

Linux網路程式設計 I O復用之poll函式

目前幾乎在所有的平台上支援,其良好跨平台支援也是它的乙個優點1.每次呼叫 select 都需要把 fd 集合從使用者態拷貝到核心態,這個開銷在 fd 很多時會很大,同時每次呼叫 select 都需要在核心遍歷傳遞進來的所有 fd,這個開銷在 fd 很多時也很大。2.單個程序能夠監視的檔案描述符的數量...

Linux網路程式設計 I O復用之poll函式

小哥整理的不錯,對一些基礎的東西總結的比較全面。一 回顧前面的select select優點 目前幾乎在所有的平台上支援,其良好跨平台支援也是它的乙個優點 select缺點 1.每次呼叫 select 都需要把 fd 集合從使用者態拷貝到核心態,這個開銷在 fd 很多時會很大,同時每次呼叫 sele...

網路程式設計 poll

寫下來,怕忘記了 server include include include include include include include include gettimeofday include struct in addr include inet aton include getpid i...