C IO 复用 poll

xiaoxiao2021-02-28  4

1、poll的机制与select类似,与select在本质上没有多大差别,管理多个描述符也是进行轮询,根据描述符的状态进行处理,但是poll没有最大文件描述符数量的限制。poll和select同样存在一个缺点就是,包含大量文件描述符的数组被整体复制于用户态和内核的地址空间之间,而不论这些文件描述符是否就绪,它的开销随着文件描述符数量的增加而线性增大。

2、poll 和select的区别2,将读事件和写事件区分

#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <poll.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <ctype.h> #define OPEN_MAX 1024 #define MAXLINE 128 int main(){ int listenfd,i,maxi,nready,connfd,sockfd,n,j,opt=1; char buf[MAXLINE]; if((listenfd = socket(AF_INET,SOCK_STREAM,0))==0){ perror("socket"); return 1; } struct sockaddr_in addr,cliaddr; socklen_t cliaddr_len=sizeof(cliaddr); struct pollfd client[OPEN_MAX]; addr.sin_family = AF_INET; addr.sin_port = htons(7777); addr.sin_addr.s_addr = INADDR_ANY; setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)); if(bind(listenfd,(struct sockaddr *)&addr,sizeof(addr))==-1){ perror("bind"); return 2; } if(listen(listenfd,128)==-1){ perror("listen"); return 3; } client[0].fd = listenfd; client[0].events = POLLRDNORM; for(i=1;i<OPEN_MAX;i++){ client[i].fd = -1; } maxi = 0; while(1){ nready = poll(client,maxi+1,-1); if(client[0].revents & POLLRDNORM){ connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&cliaddr_len); printf("received from %s at PORT %d\n",inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port)); for(i=1;i<OPEN_MAX;i++){ if(client[i].fd <0){ client[i].fd = connfd; break; } } if(i==OPEN_MAX){ perror("too many clients"); exit(1); } client[i].events = POLLRDNORM; if(i>maxi){ maxi = i; } if(--nready<=0){ continue; } } for(i=1;i<=maxi;i++){ if((sockfd=client[i].fd)<0){ continue; } if(client[i].revents &(POLLRDNORM |POLLERR)){ if((n=read(sockfd,buf,MAXLINE))<0){ if(errno==ECONNRESET){ printf("client [%d] aborted connection\n",i); close(sockfd); client[i].fd = -1; }else{ perror("read error"); } }else if(n==0){ printf("client [%d] closed connection\n",i); close(sockfd); client[i].fd = -1; }else{ for(j = 0;j<n;j++){ buf[j] = toupper(buf[j]); } write(sockfd,buf,n); } if(--nready<=0){ break; } } } } return 0; }
转载请注明原文地址: https://www.6miu.com/read-1950184.html

最新回复(0)