poll 函数和 select 函数功能类似,但是poll没有最大描述符个数限制。
1.函数定义:
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
参数:
fds: 指向一个结构体数组的第0个元素的指针,每个数组元素都是一个struct pollfd结构。
struct pollfd{
int fd; //文件描述符,指定被监视的文件描述符。
short events; //等待的事件,指定监测fd的事件(输入、输出、错误)。
short revents; //实际发生的事件,文件描述符的操作结果事件。内核在调用返回时设置这个域。events 域中请求的任何事件都可能在 revents 域中返回。
events事件如下:
nfds:用来指定第一个参数数组元素个数
timeout:指定等待的毫秒数,无论 I/O 是否准备好,poll() 都会返回.
返回值:
成功时,poll() 返回结构体中 revents 域不为 0 的文件描述符个数;如果在超时前没有任何事件发生,poll()返回 0;
失败时,poll() 返回 -1,并设置 errno 为下列值之一:
EBADF:一个或多个结构体中指定的文件描述符无效。
EFAULT:fds 指针指向的地址超出进程的地址空间。
EINTR:请求的事件之前产生一个信号,调用可以重新发起。
EINVAL:nfds 参数超出 PLIMIT_NOFILE 值。
ENOMEM:可用内存不足,无法完成请求。
2.函数使用:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/time.h>
#include<unistd.h>
#include<string.h>
#include <poll.h>
int main()
{
int sockfd; //套接字句柄, 来自socket
sockfd = //sock/bind/listen
struct pollfd pollfds;
int timeout;
timeout = 5000;
pollfds.fd = sockfd; //设置监控sockfd
pollfds.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;
}
}
}