Linux下select函式的使用

2021-07-03 19:32:22 字數 2092 閱讀 5263

一.select 函式詳細介紹

負值:select錯誤 

正值:某些檔案可讀寫或出錯 

0:等待超時,沒有可讀寫或錯誤的檔案 

在有了select後可以寫出像樣的網路程式來!

舉個簡單的例子,就是從網路上接受資料寫入乙個檔案中。 

main()  

; //select等待3秒,3秒輪詢,要非阻塞就置0

char

buffer[256]=; 

//256位元組的接收緩衝區

/* 假定已經建立udp連線,具體過程不寫,簡單,當然tcp也同理,主機ip和port都已經給定,要寫的檔案已經開啟

sock=socket(...);

bind(...);

fp=fopen(...); */

while

(1)  

// end if break;

}// end switch

}//end while

}//end main 

二.另乙個例子:

#include

#include

#include

定義函式 int select(int n,fd_set * readfds,fd_set * writefds,fd_set * exceptfds,struct timeval * timeout);

函式說明 select()用來等待檔案描述詞狀態的改變。引數n代表最大的檔案描述詞加1,引數readfds、writefds 和exceptfds 稱為描述片語,是用來回傳該描述詞的讀,寫或例外的狀況。底下的巨集提供了處理這三種描述片語的方式:

fd_clr(inr fd,fd_set* set);用來清除描述片語set中相關fd 的位  

fd_isset(int

fd,fd_set *set);用來測試描述片語set中相關fd 的位是否為真  

fd_set(int

fd,fd_set*set);用來設定描述片語set中相關fd的位  

fd_zero(fd_set *set); 用來清除描述片語set的全部位  

引數 timeout為結構timeval,用來設定select()的等待時間,其結構定義如下  

struct

timeval  

;   

返回值 如果引數timeout設為null則表示select()沒有timeout。

錯誤** 執行成功則返回檔案描述詞狀態已改變的個數,如果返回0代表在描述詞狀態改變前已超過timeout時間,當有錯誤發生時則返回-1,錯誤原因存於errno,此時引數readfds,writefds,exceptfds和timeout的值變成不可**。

ebadf 檔案描述詞為無效的或該檔案已關閉

eintr 此呼叫被訊號所中斷

einval 引數n 為負值。

enomem 核心記憶體不足

範例 常見的程式片段:fs_set readset;

fd_zero(&readset);

fd_set(fd,&readset);

select(fd+1,&readset,null,null,null);

if(fd_isset(fd,readset)

下面是linux環境下select的乙個簡單用法

#i nclude 

#i nclude 

#i nclude 

#i nclude 

#i nclude 

#i nclude 

intmain ()  

}  }   

用來迴圈讀取鍵盤輸入

將例子程式作一修改,加上了time out,並且考慮了select得所有的情況:

#include 

#include 

#include 

#include 

#include 

intmain ()  

}  //time out when ret = 0

else

if(ret == 0)  

printf("time out/n"

);  

}  }  

linux下的Select函式

part1 fd set errorfds同上面兩個引數的意圖,用來監視檔案錯誤異常。struct timeval timeout是select的超時時間,這個引數至關重要,它可以使select處於三種狀態,第一,若將null以形參傳入,即不傳入時間結構,就是將select置於阻塞狀態,一定等到監視...

linux下select函式的使用

先看下列的例子程式 include include include include define stdin 0 define true 1 define false 0 define ulong unsigned long static struct timeval timelast static...

Linux下select函式的使用

一.select 函式詳細介紹 負值 select錯誤 正值 某些檔案可讀寫或出錯 0 等待超時,沒有可讀寫或錯誤的檔案 在有了select後可以寫出像樣的網路程式來!舉個簡單的例子,就是從網路上接受資料寫入乙個檔案中。main select等待3秒,3秒輪詢,要非阻塞就置0 char buffer...