不同與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;
}