多路复用不关有select函数,还有poll函数
poll()函数
头文件:#include<sys/types.h>
#include <poll.h>
功能:把当前的文件指针挂到等待队列
原型:intpoll(struct pollfd *fd,int numfds,int timeout)
说明:fds:用于描述需要对哪些文件的哪种类型的操作进行监控,numfds:需要监听的文件个数,即第一个参数所指向的数组中的元素数目,timeout:阻塞的超时时间,精确到毫秒级别,如果小于0,表示无限等待。
返回值:
示例:
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <poll.h>
#define MAX_BUFSIZE 1024
#define IN_FILES 3
#define TIME_OUT 60000
#define MAX(a,b) ((a > b) ? (a): (b))
int main(void)
{
struct pollfd fds[IN_FILES];
char buf[MAX_BUFSIZE];
int i,res,real_read,maxfd;
/*open two source files with somepermission*/
fds[0].fd = 0;
if((fds[1].fd =open("in1",O_RDONLY|O_NONBLOCK)) < 0)
{
printf("open in1 error!\n");
return 1;
}
if((fds[2].fd =open("in2",O_RDONLY|O_NONBLOCK)) < 0)
{
printf("open in2 error!\n");
return 1;
}
/*achieve the bigger one from twofiledescriptions*/
for(i = 0; i < IN_FILES;i++)
{
fds[i].events = POLLIN;
}
while(fds[0].events || fds[1].events ||fds[2].events)
{
if(poll(fds,IN_FILES,0) < 0)
{
printf("Poll error or timeout\n");
return 1;
}
for(i = 0;i < IN_FILES;i++)
{
if(fds[i].events)
{
memset(buf,0,MAX_BUFSIZE);
real_read =read(fds[i].fd,buf,MAX_BUFSIZE);
if(real_read < 0)
{
if(errno != EAGAIN)
{
return 1;
}
}
else if(!real_read)
{
close(fds[i].fd);
fds[i].events = 0;
}
else{
if(i == 0)
{
if((buf[0] == 'q') ||(buf[0] == 'Q'))
{
return 1;
}
}
else{
buf[real_read] = '\0';
printf("%s",buf);
}
}
}
}
}
exit(0);
}