I/O多路转接之epoll

来源:互联网 发布:阿里孙正义马云占股份 编辑:程序博客网 时间:2024/05/17 05:06

epoll工作原理:
epoll同样只告知那些就绪的文件描述符,而且当我们调用epoll_wait()获得就绪文件描述符时,返回的不是实际的描述符,而是一个代表就绪描述符数量的值,你只需要去epoll指定的一个数组中依次取得相应数量的文件描述符即可。

epoll的相关系统调用:

1、 int epoll_create(int size):创建一个epoll的句柄,size可忽略。当创建好epoll句柄后,它就是会占⽤用一个fd值,所以在使用完epoll后,必须调用close()关闭,否则可能导致fd被耗尽。

2、int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event):epoll的事件注册函数,在这里先注册要监听的事件类型。
第一个参数是epoll_create()的返回值。
第二个参数表示动作,用三个宏来表示:
EPOLL_CTL_ADD:添加所关心的事件;
EPOLL_CTL_MOD:修改已经注册的fd的监听事件;
EPOLL_CTL_DEL:从epfd中删除一个fd;
第三个参数是需要监听的fd。
第四个参数是告诉内核需要监听什么事。
struct epoll_event结构如下:
这里写图片描述
events可以是以下几个宏的集合:
EPOLLIN :表示对应的文件描述符可以读(包括对端SOCKET正常关闭);
EPOLLOUT:表示对应的文件描述符可以写;
EPOLLPRI:表示对应的文件描述符有紧急的数据可读(这里应该表示有带外(紧急)数据到来);
EPOLLERR:表示对应的文件描述符发生错误;
EPOLLHUP:表示对应的文件描述符被挂断;
EPOLLET: 将EPOLL设为边缘触发(Edge Triggered)模式,这是相对于水平触发(LevelTriggered)来说的。
EPOLLONESHOT:只监听一次事件,当监听完这次事件之后,如果还需要继续监听这个socket的话,需要再次把这个socket加入到EPOLL队列里。

3、 int epoll_wait(int epfd, struct epoll_event * events, int maxevents, int timeout):收集在epoll监控的事件中已经发送的事件。
events是分配好的epoll_event结构体数组,epoll将会把发生的事件赋值到events数组中(events不可以是空指针,内核只负责把数据复制到这个events数组中,不会去帮助我们在用户态中分配内存)。
maxevents告之内核这个events有多⼤大,这个 maxevents的值不能⼤大于创建epoll_create()时的size。
timeout是超时时间(毫秒),0表示非阻塞,会立即返回;-1将不确定,也有说法说是永久阻塞。大于0表示timeout时间轮询返回。

epoll下面维护了两个重要的数据结构:

红黑树:存放所关心的所有文件描述符的所有事件。
队列:回调函数把就绪事件的文件描述符从红黑树拷贝到队列中。

服务器端代码:

#include<stdio.h>#include<sys/epoll.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/in.h>#include<arpa/inet.h>#include<stdlib.h>#include<string.h>static void usage(const char *proc){  printf("usage:%s [local_ip] [local_port]",proc);}typedef struct fd_buf{  int fd;  char buf[10240];}fd_buf_t,*fd_buf_p;static void *alloc_fd_buf(int fd){ fd_buf_p tmp=(fd_buf_p)malloc(sizeof(fd_buf_t)); if(!tmp) {   perror("malloc");   return NULL; } tmp->fd=fd; return tmp;}int startup(const char *_ip,const int _port){ int sock=socket(AF_INET,SOCK_STREAM,0); if(sock<0) {   perror("socket");   return 2; } struct sockaddr_in local; local.sin_family=AF_INET; local.sin_port=htons(_port); local .sin_addr.s_addr=inet_addr(_ip); if(bind(sock,(struct sockaddr*)&local,sizeof(local))<0) {  perror("bind");  return 3; } if(listen(sock,10)<0) {  perror("listen");  return 4; } return sock;}int main(int argc,char *argv[]){  if(argc!=3)  {    usage(argv[0]);    return 1;  }  int listen_sock=startup(argv[1],atoi(argv[2]));  //创建epoll句柄  int epfd=epoll_create(256);  if(epfd<0)  {     printf("epoll_create");     close(listen_sock);     return 5;  }  struct epoll_event ev;  ev.events=EPOLLIN;  ev.data.ptr=alloc_fd_buf(listen_sock);  epoll_ctl(epfd,EPOLL_CTL_ADD,listen_sock,&ev);  int num=0;  struct epoll_event evs[64];  int timeout=-1;  while(1)  {   switch((num=epoll_wait(epfd,evs,64,timeout)))   {     //超时         case 0:         perror("timeout...");         break;     //等待失败      case -1:         perror("epoll_wait");         break;     //正确,返回就绪文件描述符个数     default:         {           int i=0;           for(;i<num;i++)           {            fd_buf_p fp=(fd_buf_p)evs[i].data.ptr;            if(fp->fd==listen_sock && \                    (evs[i].events & EPOLLIN))            {            struct sockaddr_in client;            socklen_t len=sizeof(client);            int new_sock=accept(listen_sock,\                    (struct sockaddr*)&client,&len);            if(new_sock<0)            {                perror("accept");                continue;            }            printf("get a new client\n");            ev.events=EPOLLIN;            ev.data.ptr=alloc_fd_buf(new_sock);            epoll_ctl(epfd,EPOLL_CTL_ADD,\                    new_sock,&ev);            }            else if(fp->fd!=listen_sock)            {            //监听到读事件             if(evs[i].events & EPOLLIN)             {               ssize_t s=read(fp->fd,fp->buf,sizeof(fp->buf));               if(s>0)               {                fp->buf[s]=0;                printf("client say:%s\n",fp->buf);                ev.events=EPOLLOUT;                ev.data.ptr=fp;                epoll_ctl(epfd,EPOLL_CTL_MOD,fp->fd,&ev);               }               else if(s<=0)               {                close(fp->fd);                epoll_ctl(epfd,EPOLL_CTL_DEL,fp->fd,NULL);                free(fp);               }                else{}             }             //监听到写事件             else if(evs[i].events & EPOLLOUT)             {              const char *msg="HTTP/1.0 200 OK\r\n\r\n<html><h1>hello epoll</h1></html>";              write(fp->fd,msg,strlen(msg));              close(fp->fd);              epoll_ctl(epfd,EPOLL_CTL_DEL,fp->fd,NULL);              free(fp);             }             else{}            }            else{}           }         }   break;   }  }  return 0;}