Linux socket之四:使用POLL機制處理多串連

來源:互聯網
上載者:User

        使用select函數可以處理socket多串連的問題(select的用法參見:http://blog.csdn.net/zhandoushi1982/article/details/5070107),使用POLL也可以實現同樣的功能,且調用方式更加簡單。原型是:

struct pollfd { int fd;//檔案描述符 short events;//要求查詢的事件掩碼 short revents;//返回的事件掩碼};int poll(struct pollfd *ufds, unsigned int nfds, int timeout);

         poll函數使用pollfd類型的結構來監控一組檔案控制代碼,ufds是要監控的檔案控制代碼集合,nfds是監控的檔案控制代碼數量,timeout是等待的毫秒數,這段時間內無論I/O是否準備好,poll都會返回。timeout為負數表示無線等待,timeout為0表示調用後立即返回。執行結果:為0表示逾時前沒有任何事件發生;-1表示失敗;成功則返回結構體中revents不為0的檔案描述符個數。pollfd結構監控的事件類型如下:

#define POLLIN 0x0001#define POLLPRI 0x0002#define POLLOUT 0x0004#define POLLERR 0x0008#define POLLHUP 0x0010#define POLLNVAL 0x0020#define POLLRDNORM 0x0040#define POLLRDBAND 0x0080#define POLLWRNORM 0x0100#define POLLWRBAND 0x0200#define POLLMSG 0x0400#define POLLREMOVE 0x1000#define POLLRDHUP 0x2000

      如上是events事件掩碼的範圍,POLLIN|POLLPRI類似於select的讀事件,POLLOUT|POLLWRBAND類似於select的寫事件。當events屬性為POLLIN|POLLOUT,表示監控是否可讀或可寫。在poll返回時,即可通過檢查revents變數對應的標誌位與events是否相同,比如revents中POLLIN事件標誌位被設定,則表示檔案描述符可以被讀取。程式碼片段樣本:

int sockfd;//通訊端控制代碼struct pollfd pollfds;int timeout;timeout = 5000;pollfds.fd = sockfd;//設定監控sockfdpollfds.events = POLLIN|POLLPRI;//設定監控的事件for(;;){switch(poll(&pollfds,1,timeout)){//開始監控case -1://函數調用出錯printf("poll error \r\n");break;case 0:printf("time out \r\n");break;default://得到資料返回printf("sockfd have some event \r\n");printf("event value is 0x%x",pollfds.revents);break;}} 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.