IO复用——poll系统调用

1、poll函数

#include<poll.h>
int poll(struct pollfd* fds, nfds_t ndfs, int timeout)

    poll函数在一定的时间内轮询一定数量的文件描述符,检测是否有文件描述符就绪。参数解析如下:

  • fds为一个pollfd结构类型数组,用来指定用户感兴趣的文件描述符,并返回文件描述符上发生的可读、可写和异常事件 
  • nfds指定被监听事件集合fds的大小,类型定义为typedef unsigned long int nfds_t
  • timeout指定超时时间,单位为毫秒,timeout为-1时,poll永远阻塞,知道某个事件发生,为0时,poll调用立即返回
  • poll函数的返回值与select函数的返回值含义相同

    pollfd结构定义如下:

struct pollfd
{
    int fd;         //文件描述符
    short events;   //注册的时间,一系列事件的按位或
    short revents;  //实际发生的事件,由内核修改,用来通知应用程序fd上发生的事件
}

2、索引poll返回的就绪文件描述符程序示例

int ret = poll(fds, MAX_EVENT_NUM, -1)
for(int i = 0; i < MAX_EVENT_NUM; i++)
{
	if(fds[i].revents & POLLIN)  //判断第i个文件描述符是否读就绪
	{
		int socket = fds[i].fd;

		//处理socket
		
	}
}	

猜你喜欢

转载自blog.csdn.net/fangyan5218/article/details/80243960