當(dāng)前位置:首頁 > 嵌入式培訓(xùn) > 嵌入式學(xué)習(xí) > 講師博文 > select、pselect和poll函數(shù)的區(qū)別及用法
下面我們說一下select、pselect和poll函數(shù)的具體用法及區(qū)別
• select
對于fd_set數(shù)據(jù)類型,唯一可以進(jìn)行的處理是:分配一個這種類型的變量,將這種類型的一個變量值賦給同類型的另一個變量,或?qū)@種類型的變量使用下列4個函數(shù)中的一個:
具體使用方法;
需要注意:
【1】函數(shù)的實(shí)現(xiàn)里面返回的話會修改timeval中的值,linux中會用剩余的時間值更新struct timeval結(jié)構(gòu),所以每次調(diào)用select都需要重新設(shè)置timeval的值。
【2】文件描述符集合也一樣,select返回的話(無論是何種方式返回)會將沒準(zhǔn)備好的文件描述符從集合中清空,所以每次調(diào)用select函數(shù)前需要設(shè)置其文件描述符集合。
【3】當(dāng)設(shè)置超時檢測時,超時了的話select返回0,如果在等待的過程中被信號中斷,那么其出錯返回-1,并且設(shè)置相應(yīng)的errno而EINTR。
【4】第一個參數(shù)為大的文件描述符值(三個文件描述符集中大值)加1。因?yàn)樾枰膮?shù)是文件描述符的個數(shù),而它是從0開始編號的。
【5】所謂“準(zhǔn)備好”,也就是說對其進(jìn)行read或write操作不會阻塞,則認(rèn)為其實(shí)準(zhǔn)備好的。
【6】當(dāng)socket進(jìn)入select時,另一個線程調(diào)用close關(guān)掉該socket,select不能退出等待并返回。
這個行為是未指定的,man文檔中有說明
Multithreaded applications
If a file descriptor being monitored by select() is closed in another thread, the result is unspecified. On some UNIX systems, select() unblocks and
returns, with an indication that the file descriptor is ready (a subsequent I/O operation will likely fail with an error, unless another the file descriptor
reopened between the time select() returned and the I/O operations was performed). On Linux (and some other systems), closing the file descriptor in
another thread has no effect on select(). In summary, any application that relies on a particular behavior in this scenario must be considered buggy.
• pselect
除下列幾點(diǎn),select與pselect相同
1、select的超時值用timaval結(jié)構(gòu),成員為秒和微秒;pselect的超時值用timespec結(jié)構(gòu),成員為秒和納秒。
2、pselect的超時值被聲明為const,這保證了調(diào)用pselect返回后不會改變其設(shè)定的超時值。
3、pselect的后一個參數(shù)可以指定一個信號屏蔽字。如果填NULL則在于信號有關(guān)的方面select和pselect是相同的。否則,sigmask指向一有效的信號屏蔽字,在調(diào)用pselect時,以原子操作的方式安裝該信號屏蔽字,在返回時,恢復(fù)以前的信號屏蔽字。
• poll
具體使用方法:
poll不會為每個條件(可讀、可寫和異常條件)構(gòu)造一個描述符集,而是構(gòu)造一個pollfd結(jié)構(gòu)的數(shù)組,而每個數(shù)組元素指定一個描述符編號以及我們對該描述符該興趣的條件。
應(yīng)為每個數(shù)組元素的events成員設(shè)置為下圖中值的一個或幾個,通過這些值告訴內(nèi)核我們關(guān)心的是每個描述符的哪些事件。返回時,revents成員由內(nèi)核設(shè)置,用于說明每個描述符發(fā)生了哪些事件。注意,poll沒有更改events成員,這與select不同。
第三個參數(shù)的精度為毫秒,如果系統(tǒng)不提供毫秒級精度,則timeout值取整到近的支持值。