Linux环境下用于I/O多路复用的系统函数poll浅析

Poll是Linux中的字符设备驱动中的一个函数。Linux 2.5.44版本后,poll被epoll取代。和select实现的功能差不多,poll的作用是把当前的文件指针挂到等待队列。

一、 poll函数

poll函数定义如下:

#include <poll.h>

int poll(struct pollfd *fds, nfds_t nfds, int timeout);

pollfd结构体定义如下:

struct pollfd {
    int   fd;         /* file descriptor */
    short events;     /* requested events */
    short revents;    /* returned events */
};

二、 测试程序

Linux系统编程上关于poll的例子很棒,结构清晰易懂。

#include <stdio.h>
#include <unistd.h>
#include <poll.h>

#define TIMEOUT 5000

int main(void)
{
	int retval;
	struct pollfd fds[2];

	fds[0].fd = STDIN_FILENO;
	fds[0].events = POLLIN;

	fds[1].fd = STDOUT_FILENO;
	fds[1].events = POLLOUT;

	if((retval = poll(fds, 2, TIMEOUT)) < 0)
	{
		perror("poll error\n");
		return 1;
	}
	
	if(retval == 0)
	{
		printf("%d seconds elapsed.\n", TIMEOUT/1000);
		return 0;
	}
	
	if(fds[0].revents & POLLIN)
	{
		printf("stdin is readable\n");
	}
	
	if(fds[1].revents & POLLOUT)
	{
		printf("stdout is writable\n");
	}
	
	return 0;
}

测试结果如下:

[ycxie@fedora Workspace]$ gcc polldemo.c -o polldemo -Wall
[ycxie@fedora Workspace]$ ./polldemo
stdout is writable
[ycxie@fedora Workspace]$ ./polldemo < polldemo.c
stdin is readable
stdout is writable

Leave a Reply

Your email address will not be published. Required fields are marked *