您的位置:首页 > 运维架构 > Linux

【Linux】多路复用之—poll

2016-05-21 20:12 696 查看
一:多路复用之——poll

#include<poll.h>

int poll(struct pollfd *fs,nfds_t nfds,int timeout)

1、参数:

struct pollfd{

int fd 关心的文件描述符

short events 关心的事件

short revents 实际发生的事件

}

2、nfds、timeout和select一样

3、宏:

(1)POLLIN:有数据可读;

(2)POLLOUT:有数据可写;

(3)POLLPRI:有紧迫数据可读;

4、返回值:

0:超时返回

-1:失败

>0:返回文件描述符集中改变状态的文件描述符个数

5、理解poll模型:

poll的机制与select类似,与select在本质上没有什么区别,管理多个文件描述符也是进行轮询,根据描述符的状态进行处理,但是poll没有最大文件描述符数量的限制。

poll和select同样存在一个缺点就是,包含大量文件描述符的数组被整体复制于用户态和内核的地址空间之间,而不论这些文件描述符是否就绪,它的开销随文件描述符数量

的增加而线性增大。

代码示例:

my_poll.c

<span style="font-size:14px;">#include<stdio.h>
#include<errno.h>
#include<string.h>
#include<poll.h>
int main()
{
int read_fd=0;
int write_fd=1;
struct pollfd _poll_fd[2];
_poll_fd[0].fd=read_fd;
_poll_fd[1].fd=write_fd;
_poll_fd[0].events=POLLIN;
_poll_fd[1].events=POLLOUT;
_poll_fd[0].revents=0;
_poll_fd[1].revents=0;
nfds_t fds=2;
int timeout=1000;
char buf[1024];
memset(buf,'\0',sizeof(buf));
while(1){
switch(poll(_poll_fd,2,timeout)){
case 0:
printf("timeout\n");
break;
case -1:
perror("poll");
break;
default:
{
//int i=0;
if((_poll_fd[0].revents) & (POLLIN)){
ssize_t _size=read(0,buf,sizeof(buf)-1);
if(_size>0){
buf[_size]='\0';
if((_poll_fd[1].revents) & (POLLOUT)){
printf("%s\n",buf);
}
}
}
}
break;
}
}
return 0;
}</span>


Makefile:

my_poll:my_poll.c
gcc -o $@ $^
.PHONY:clean
clean:
rm -rf my_poll
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: