【計算機網絡】I/O多路轉接之poll

不同與select使用三個位圖來表示三個fdset的方式,poll使用一個 pollfd的指針實現。
這裏寫圖片描述
pollfd結構包含了要監視的event和發生的event,不再使用select“參數-值”傳遞的方式。同時,pollfd並沒有最大數量限制(但是數量過大後性能也是會下降)。 和select函數一樣poll返回後,需要輪詢pollfd來獲取就緒的描述符。
從上面看,select和poll都需要在返回後,通過遍歷文件描述符來獲取已經就緒的socket。事實上,同時連接的大量客戶端在某時刻可能只有很少的處於就緒狀態,因此隨着監視的描述符數量的增長,其效率也會線性下降。
這裏寫圖片描述
使用poll監控輸入輸出

#include<stdlib.h>
#include<string.h>
#include<poll.h>
#include<sys/types.h>
#include<stdio.h>
int mypoll()
{
    struct pollfd poll_set[1];
    poll_set[0].fd=0;
    poll_set[0].events=POLLIN;
    poll_set[0].revents=0;
    int timeout=5000;
    char buf[1024];
    while(1)
    {
        switch(poll(poll_set,1,timeout))
        {
            case -1:
                perror("poll");
                exit(1);
                break;
            case 0:
                printf("poll timeout!\n");
                break;
            default:
                {
                    memset(buf,'\0',sizeof(buf));
                    printf("poll return for poll\n");
                    fgets(buf,sizeof(buf)-1,stdin);
                    printf("msg is:%s\n",buf);
                }
                break;

        }
    }
    return 0;
}
int main()
{
    mypoll();
    return 0;
}

這裏寫圖片描述

發佈了157 篇原創文章 · 獲贊 121 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章