【Linux】多路复用之—poll

一:多路复用之——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



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值