歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux技術 >> 【Linux】多路復用之—poll

【Linux】多路復用之—poll

日期:2017/3/3 12:32:49   编辑:Linux技術

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

Copyright © Linux教程網 All Rights Reserved