poll提供的功能与select类似,不过在处理流设备时,它能够提供额外的信息。
#include <poll.h>
int poll(struct pollfd pollfd[],nfds_t nfds,int timeout);
参数:
struct pollfd{
int fd; //关注的文件描述符
short events; //感兴趣的事件
short revents; //内核实际返回的事件(用作最终判断)
};
ndfs: pollfd数量
timeout:(time==负值?无限等待:实际时间)
- The caller should specify the number of items in the fds array in nfds.The field fd contains a file descriptor for an open file.
- The field events is an input parameter, a bit mask specifying the events the appli‐cation is interested in.
- The field revents is an output parameter, filled by the kernel with the events that actually occurred. The bits returned in revents can include any of those specified in events, or one of the values POLLERR, POLLHUP, or POLLNVAL. (These three bits are meaningless in the events field, and will be set in the revents field whenever the corresponding condition is true.)
- The timeout argument specifies an upper limit on the time for which poll() will block, in milliseconds. Specifying a negative value in timeout means an infinite timeout.
常量 说明
POLLIN 普通或优先级带数据可读
POLLRDNORM 普通数据可读
POLLRDBAND 优先级带数据可读
POLLPRI 高优先级数据可读
POLLOUT 普通数据可写
POLLWRNORM 普通数据可写
POLLWRBAND 优先级带数据可写
POLLERR 发生错误
POLLHUP 发生挂起
POLLNVAL 描述字不是一个打开的文件
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <stropts.h>
#include <sys/poll.h>
#include <sys/stropts.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <poll.h>
#define BUFSIZE 1024
int main(int argc, char *argv[])
{
char buf[BUFSIZE];
int bytes;
struct pollfd *pollfd;
int i=0;
int nummonitor=0;
int numready;
int errno;
char *str;
if(argc != 3)
{
fprintf(stderr,"Usage:the argc num error\n");
exit(1);
}
//为struct pollfd分配空间
if((pollfd = (struct pollfd*)calloc(2, sizeof(struct pollfd))) == NULL)
exit(1);
//初始化化struct pollfd结构
for(i; i<2; i++){
str = (char*)malloc(14*sizeof(char));
memcpy(str,"/root/pro/",14);
strcat(str,argv[i+1]);
printf("str=%s\n",str);
(pollfd+i)->fd = open(str,O_RDONLY);
if((pollfd+i)->fd >= 0)
fprintf(stderr, "open (pollfd+%d)->fd:%s\n", i, argv[i+1]);
nummonitor++;
(pollfd+i)->events = POLLIN;
}
printf("nummonitor=%d\n",nummonitor);
while(nummonitor > 0){
numready = poll(pollfd, 2, -1);
//被信号中断,继续等待
if ((numready == -1) && (errno == EINTR))
continue;
else if (numready == -1)//poll真正错误,退出
break;
printf("numready=%d\n",numready);
for (i=0;nummonitor>0 && numready>0; i++)
{
//返回内核做判断
if((pollfd+i)->revents & POLLIN)
{
bytes = read(pollfd[i].fd, buf, BUFSIZE);
numready--;
printf("pollfd[%d]->fd read buf:\n%s \n", i, buf);
nummonitor--;
}
}
}
for(i=0; i<nummonitor; i++)
close(pollfd[i].fd);
free(pollfd);
return 0;
}