Linux網絡編程---I/O復用模型之poll

https://blog.csdn.net/men_wen/article/details/53456474

Linux網絡編程—I/O復用模型之poll

1.函數poll

poll系統調用和select類似,也是在指定時間內輪詢一定數量的文件描述符,以測試其中是否有就緒者。

#include <poll.h>int poll(struct pollfd *fds, nfds_t nfds, int timeout);
//返回值:若成功,返回就緒的描述符個數,若超時則為0,若出錯則為-1
  • fds是指向一個pollfd結構第一個元素的指針。每一個元素都是pollfd結構類型,用于測試某個給定描述符fd的條件
struct pollfd {int   fd;         /* file descriptor */short events;     /* requested events */short revents;    /* returned events */
};

要測試的條件在events中指定,函數相應的revents成員返回該描述符的狀態,一個為調用值,一個為返回結果,這與select的傳入傳出參數不同。?
events和revents可以設置以下常量的一個或多個的按位或結果:

POLLIN      //普通或帶外優先數據可讀,即POLLRDNORM | POLLRDBAND
POLLRDNORM  //數據可讀
POLLRDBAND  //優先級帶數據可讀
POLLPRI     //高優先級可讀數據
POLLOUT     //普通或帶外數據可寫
POLLWRNORM  //數據可寫
POLLWRBAND  //優先級帶數據可寫
//下面三個revents不包含
POLLERR     //發生錯誤
POLLHUP     //發生掛起
POLLNVAL    //描述字不是一個打開的文件
  • out指定poll函數返回前等待多長時間,它是一個指定應等待毫秒數的正值。

|timeout值|說明|?
|:-:|:-:|?
|-1|永遠等待|?
|0|立即返回,不阻塞進程|?
|>0|等待指定數目的毫秒數|

  • nfds 是監控數組中有多少文件描述符需要被監控

如果我們不關心某個特定的描述符,那么可以把與它對應的pollfd結構的fd成員設置為一個負值。poll函數會忽略這樣的pollfd結構的events成員,返回時將其revents成員的值置為0。

select模型最多可以創建一個1024個文件描述符大小的集合,這是因為受到fd_set的固定數據類型的限制,而poll則沒有這樣的問題,因為分配一個pollfd結構的數組并把數組中的元素通知內核稱為調用者的責任。但是poll模型任然使用的是輪詢模型,效率比較低下。

2. poll模型實現

2.1 服務器端

#include "wrap.h"
#include <poll.h>
#include <limits.h>
#include <sys/stropts.h>#define MAXLINE         1024
#define INFTIM          -1
#define OPEN_MAX        3000
int main(int argc, char *argv[])
{int i, maxi, listenfd, connfd, sockfd;int nready;ssize_t n;char buf[MAXLINE];socklen_t clilen;struct pollfd client[OPEN_MAX];struct sockaddr_in clientaddr;listenfd = start_ser(argv[1], argv[2]);//監聽文件描述符  該函數參考selectclient[0].fd = listenfd;//將監聽文件描述符加入pollfd數組中client[0].events = POLLIN;//設置為輸入可讀for(i = 1; i < OPEN_MAX; i++){//初始化結構體數組client[i].fd = -1;}maxi = 0;while(1){nready = poll(client, maxi+1, INFTIM);  //阻塞等待注冊時間發生if(client[0].revents & POLLIN){//當監聽文件描述符響應有新連接請求clilen = sizeof(clientaddr);connfd = Accept(listenfd, (struct sockaddr *)&clientaddr, &clilen);//接受新客戶for(i = 1; i < OPEN_MAX; i++){if(client[i].fd < 0){client[i].fd = connfd;  //把新客戶的文件描述符加入數組break;}}if(i == OPEN_MAX){      //連接新客戶上限Close(connfd);perr_exit("too many clients");}client[i].events = POLLIN;      //新客戶端的處理事件if(i > maxi){maxi = i;       //更新最大值}if(--nready == 0){      //沒有可讀的描述符跳過本次循環continue;}}for(i = 1; i <= maxi; i++){     //請求所有客戶端的數據if((sockfd = client[i].fd) < 0){continue;}if(client[i].revents & POLLIN){ //POLLIN事件發生memset(buf, '\0', MAXLINE);if((n = Read(sockfd, buf, MAXLINE-1)) < 0){if(errno == ECONNRESET){        //當客戶端發送resetClose(sockfd);client[i].fd = -1;}else{perr_exit("read err");}}else if(n == 0){Close(sockfd);client[i].fd = -1;}else{printf("client : %s\n", buf);}if(--nready == 0){      //沒有可讀的描述符跳過本次循環break;}}}}Close(connfd);Close(listenfd);return 0;
}

2.2客戶端

#include "wrap.h"int main(int argc, char *argv[])
{struct sockaddr_in serveraddr;int connfd;connfd = Socket(AF_INET, SOCK_STREAM, 0);bzero(&serveraddr, sizeof(serveraddr));serveraddr.sin_family = AF_INET;serveraddr.sin_port = htons(atoi(argv[2]));inet_pton(AF_INET, argv[1], &serveraddr.sin_addr);Connect(connfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));char buf[1024];while((fgets(buf, 1024, stdin)) != NULL){Write(connfd, buf, strlen(buf));}Close(connfd);return 0;
}

2.3程序測試結果

這里寫圖片描述

這里寫圖片描述

這里寫圖片描述


本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/383759.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/383759.shtml
英文地址,請注明出處:http://en.pswp.cn/news/383759.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

FFT模板

整理了一下&#xff0c;自己寫了一下模板 const double PIacos(-1.0); struct complex {double r,i;complex(double _r0,double _i0):r(_r),i(_i){}complex operator (const complex &b) {return complex(rb.r,ib.i);}complex operator -(const complex &b) {return c…

Linux網絡編程---I/O復用模型之epoll

https://blog.csdn.net/men_wen/article/details/53456474 Linux網絡編程—I/O復用模型之epoll 1. epoll模型簡介 epoll是Linux多路服用IO接口select/poll的加強版&#xff0c;e對應的英文單詞就是enhancement&#xff0c;中文翻譯為增強&#xff0c;加強&#xff0c;提高&…

POJ 1741tree-點分治入門

學習了一下點分治&#xff0c;如果理解有誤還請不吝賜教。 為了快速求得樹上任意兩點之間距離滿足某種關系的點對數&#xff0c;我們需要用到這種算法。 點分治是樹上的一種分治算法&#xff0c;依靠樹和子樹之間的關系進行分治從而降低復雜度。 和其他樹上的算法有一些區別…

基于單鏈表的生產者消費者問題

『生產者與消費者問題分析』「原理」生產者生產產品&#xff0c;消費者消費產品。產品如果被消費者消費完了&#xff0c;同時生產者又沒有生產出產品&#xff0c;消費者 就必須等待。同樣的&#xff0c;如果生產者生產了產品&#xff0c;而消費者沒有去消費&#x…

C++智能指針(一)智能指針的簡單介紹

https://blog.csdn.net/nou_camp/article/details/70176949C智能指針 在正式了解智能指針前先看一下下面的一段代碼 #include<iostream> using namespace std; class A { public:A():_ptr(NULL), _a(0){}~A(){} public:int* _ptr;int _a; };void test() {A a;int *p1 ne…

聰聰可可-點分治

聰聰和可可是兄弟倆&#xff0c;他們倆經常為了一些瑣事打起來&#xff0c;例如家中只剩下最后一根冰棍而兩人都想吃、兩個人都想玩兒電腦&#xff08;可是他們家只有一臺電腦&#xff09;……遇到這種問題&#xff0c;一般情況下石頭剪刀布就好了&#xff0c;可是他們已經玩兒…

C++智能指針(二)模擬實現三種智能指針

https://blog.csdn.net/nou_camp/article/details/70186721在上一篇博客中提到了Auto_ptr(C智能指針&#xff08;一&#xff09;)&#xff0c;下面進行模擬實現Auto_ptr 采用類模板實現 #include<iostream> using namespace std; template<class T> class Autoptr …

Prime Distance On Tree-樹分治+FFT

題目描述 Problem description. You are given a tree. If we select 2 distinct nodes uniformly at random, what’s the probability that the distance between these 2 nodes is a prime number? Input The first line contains a number N: the number of nodes in this…

C++智能指針(三)總結

https://blog.csdn.net/nou_camp/article/details/70195795 在上一篇博客中&#xff08;C智能指針&#xff08;二&#xff09;&#xff09;模擬實現了三種智能指針。 其中最好的就是shared_ptr,但是這并不代表它就是最完美的&#xff0c;它也有問題&#xff0c;這個問題就是循環…

POJ2114-Boatherds-樹分治

題目描述 Boatherds Inc. is a sailing company operating in the country of Trabantustan and offering boat trips on Trabantian rivers. All the rivers originate somewhere in the mountains and on their way down to the lowlands they gradually join and finally th…

c++11 你需要知道這些就夠了

https://blog.csdn.net/tangliguantou/article/details/50549751c11新特性舉著火把尋找電燈今天我就權當拋磚引玉&#xff0c;如有不解大家一起探討。有部分內容是引用自互聯網上的內容&#xff0c;如有問題請聯系我。T&& 右值引用 std::move 右值引用出現之前我們只能…

HDU5977-Garden of Eden-樹分治+FWT

題目描述 When God made the first man, he put him on a beautiful garden, the Garden of Eden. Here Adam lived with all animals. God gave Adam eternal life. But Adam was lonely in the garden, so God made Eve. When Adam was asleep one night, God took a rib fro…

C++11新特性學習

https://blog.csdn.net/tennysonsky/article/details/778170481、什么是C11C11標準為C編程語言的第三個官方標準&#xff0c;正式名叫ISO/IEC 14882:2011 - Information technology -- Programming languages -- C。在正式標準發布前&#xff0c;原名C0x。它將取代C標準第二版I…

C++ override 關鍵字用法

override關鍵字作用&#xff1a; 如果派生類在虛函數聲明時使用了override描述符&#xff0c;那么該函數必須重載其基類中的同名函數&#xff0c;否則代碼將無法通過編譯。舉例子說明struct Base {virtual void Turing() 0;virtual void Dijkstra() 0;virtual void VNeumann…

Gym - 101981I-MagicPotion-最大流

題目描述 There are n heroes and m monsters living in an island. The monsters became very vicious these days, so the heroes decided to diminish the monsters in the island. However, the i-th hero can only kill one monster belonging to the set Mi. Joe, the st…

c++仿函數 functor

https://www.cnblogs.com/decade-dnbc66/p/5347088.html內容整理自國外C教材先考慮一個簡單的例子&#xff1a;假設有一個vector<string>&#xff0c;你的任務是統計長度小于5的string的個數&#xff0c;如果使用count_if函數的話&#xff0c;你的代碼可能長成這樣&#…

HDU4812-D Tree-樹分治

題目描述 There is a skyscraping tree standing on the playground of Nanjing University of Science and Technology. On each branch of the tree is an integer (The tree can be treated as a connected graph with N vertices, while each branch can be treated as a v…

成為C++高手之實戰項目

https://blog.csdn.net/niu_gao/article/details/51458721 在內存中模擬出一副牌&#xff0c;然后模擬洗牌&#xff0c;發牌等動作。 流程是這樣的&#xff1a;構建一副牌保存到一個數組中—洗牌—創建玩家—向玩家發牌–輸出每個玩家的牌。 #include <stdio.h> #include…

C++中String類的實現

https://www.cnblogs.com/zhizhan/p/4876093.html原文&#xff1a;http://noalgo.info/382.html String是C中的重要類型&#xff0c;程序員在C面試中經常會遇到關于String的細節問題&#xff0c;甚至要求當場實現這個類。只是由于時間關系&#xff0c;可能只要求實現構造函數、…

Ubuntu軟件更新失敗

剛安裝好Ubuntu以后需要將系統的軟件都更新一下&#xff0c;但是遇到一個問題就是下載倉庫信息失敗&#xff0c;大概是這個樣子的錯誤&#xff1a; 經國遇到這樣的問題可以試一下下面這個命令&#xff1a; sudo rm -rf /var/lib/apt/lists/* sudo apt-get update參考網址&…