Linux網路程式設計 select函式詳解

2021-10-07 20:27:49 字數 1980 閱讀 3740

作用:

select函式是用來監視乙個或多個檔案控制代碼的狀態變化的,可阻塞也可不阻塞。

函式原型:

int select(int nfds, fd_set *readfds, fd_set *writefds,

fd_set *exceptfds, struct timeval *timeout);

函式引數意義:

fd_max:傳入的監視檔案描述符集合中最大的檔案描述符數值 + 1,因為select是從0開始一直遍歷到數值最大的識別符號。

readfds:檔案描述符集合,檢查該組檔案描述符的可讀性。

writefds:檔案描述符集合,檢查該組檔案描述符的可寫性。

exceptfds:檔案描述符集合,檢查該組檔案描述符的異常條件。

timeout: 時間結構體

struct timeval ;
所需標頭檔案:

#include #include #include
timeout的值為null,則將select()函式置為阻塞狀態,當監視的檔案描述符集合中的某乙個描述符發生變化才會返回結果並向下執行。

timeout的值等於0,則將select()函式置為非阻塞狀態,執行select()後立即返回,無**件描述符是否發生變化。

timeout的值大於0,則將select()函式的超時時間設為這個值,在超時時間內阻塞,超時後返回結果。

檔案描述符集合設定:

fd_zero(fd_set *fd);             /* 清空該組檔案描述符集合 */

fd_clr(inr fd,fd_set *fd); /* 清除該組檔案描述符集合中的指定檔案描述符 */

fd_isset(int fd,fd_set *fd); /* 測試指定的檔案描述符是否在該檔案描述符集合中 */

fd_set(int fd,fd_set *fd); /* 向該檔案描述符集合中新增檔案描述符 */

返回值:

注意:

每次呼叫完select()函式後需要將檔案描述符集合清空並重新設定(也可以利用另外乙個變數儲存原來的集合),也就是設定的檔案描述符集合是一次性使用的。原因是呼叫完select()後檔案描述符集合可能發生改變。

優點:跨平台。

缺點:1.每次呼叫 select(),都需要把 fd 集合從使用者態拷貝到核心態,這個開銷在 fd 很多時會很大,同時每次呼叫 select() 都需要在核心遍歷傳遞進來的所有 fd,這個開銷在 fd 很多時也很大。

2.單個程序能夠監視的檔案描述符的數量存在最大限制,在 linux 上一般為 1024,可以通過修改巨集定義甚至重新編譯核心的方式提公升這一限制,但是這樣也會造成效率的降低

例子:

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

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

// 判斷是否有新連線

if(fd_isset(lfd, &temps))

// 遍歷檢測的檔案描述符是否有讀操作

for(int i=lfd+1; i<=maxfd; ++i)

;int len = read(i, buf, sizeof(buf));

if(len == -1)

else if(len == 0)

}else

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

write(i, buf, strlen(buf)+1);}}

}}

close(lfd);

return 0;

}

linux 網路程式設計 select

include include include include include include include include include include include include typedef struct st fd def 將fd接收套接字描述符放入到fd陣列中 int add f...

Linux網路程式設計之select

使用select多路復用技術的非阻塞模型 select多路復用通常具有很好的跨平台性,也能提供不錯的併發效能,但是在通常情況下有最大監聽檔案描述符的限制 通常1024 如果不需要達到c10k這種前端高效能伺服器的要求,採用select nonblocking的方式能降低程式設計的難度 用到的介面 f...

Linux 下網路程式設計中的select

include include int select int maxfdp1,fd set readset,fd set writeset,fd set exceptset,const struct timeval timeout return 0 就緒描述字的正數目 1 出錯 0 超時 struc...