zoukankan      html  css  js  c++  java
  • 如何使用epoll? 一个C语言的简单例子 asdfjkl210 ITeye技术网站

    如何使用epoll? 一个C语言的简单例子 - asdfjkl210 - ITeye技术网站

    * How to use epoll? A complete example in C 译文

    通常的网络服务器实现, 是对每一个连接使用一个单独的线程或进程。对高性能应用而言,由于需要同时处理非常多的客户请求, 所以这种方式并不能工作得很好,因为诸如资源使用和上下文切换所需的时间影响了在一时间内对多个客户端进行处理。另一个可选的途径是在一个单独的线程里采用非阻塞的I/O, 这样当可以从一个socket中读取或写入更多数据时,由一些已经准备就绪的通知方式来告知我们。

    这篇文章介绍Linux 的 epoll方法, 它是Linux上最好的就绪通知方式。我们会写一个用C语言的TCP服务器的完全实现的简单程序。假设你已有C编程的经验,知道在Linux 下编译和运行程序, 并且会用 manpages 来查看所使用的 C 函数。

    epoll 是在 Linux 2.6 才引进的,而且它并不适用于其它 Unix-like 系统。它提供了一个与select 和 poll 函数相似的功能:
    + select 可以在某一时间监视最大达到 FD_SETSIZE 数量的文件描述符, 通常是由在 libc 编译时指定的一个比较小的数字。
    + poll 在同一时间能够监视的文件描述符数量并没有受到限制,即使除了其它因素,更加的是我们必须在每一次都扫描所有通过的描述符来检查其是否存在己就绪通知,它的时间复杂度为 O(n) ,是缓慢的。

    epoll 没有以上所示的限制,并且不用执行线性扫描。因此, 它能有更高的执行效率且可以处理大数量的事件。

    一个 epoll 实例可以通过返加epoll 实例的 epoll_create 或者 epoll_create1 函数来创建。 epoll_ctl 是用来在epoll实例中 添加/删除 被监视的文件描述符的。 epoll_wait是用来等待所监听描述符事件的,它会阻塞到事件到达。 可以在 manpages上查看更多信息。

    当描述符被添加到epoll实例中, 有两种添加模式: level triggered(级别触发) 和 edge triggered(边沿触发) 。 当使用 level triggered 模式并且数据就绪待读, epoll_wait总是会返加就绪事件。如果你没有将数据读取完, 并且调用epoll_wait 在epoll 实例上再次监听这个描述符, 由于还有数据是可读的,它会再次返回。在 edge triggered 模式时, 你只会得一次就绪通知。 如果你没有瘵数据读完, 并且再次在 epoll实例上调用 epoll_wait , 由于就绪事件已经被发送所以它会阻塞。

    传递到 epoll_ctl 的epoll事件结构体如下所示。对每一个被监听的描述符,你可以关联到一个整数或一个作为用户数据的指针。
    C代码  收藏代码
    1. typedef union epoll_data  
    2. {  
    3.   void        *ptr;  
    4.   int          fd;  
    5.   __uint32_t   u32;  
    6.   __uint64_t   u64;  
    7. } epoll_data_t;  
    8.   
    9. struct epoll_event  
    10. {  
    11.   __uint32_t   events; /* Epoll events */  
    12.   epoll_data_t data;   /* User data variable */  
    13. };  


    马上实践写代码。我们会实现一个小的TCP服务器,它会将所有SOCKET上收到的数据输出到标准输出。 首先写一个 create_and_bind() 函数,它创建并绑定一个TCP socket.

    C代码  收藏代码
    1. static int  
    2. create_and_bind (char *port)  
    3. {  
    4.   struct addrinfo hints;  
    5.   struct addrinfo *result, *rp;  
    6.   int s, sfd;  
    7.   
    8.   memset (&hints, 0, sizeof (struct addrinfo));  
    9.   hints.ai_family = AF_UNSPEC;     /* Return IPv4 and IPv6 choices */  
    10.   hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */  
    11.   hints.ai_flags = AI_PASSIVE;     /* All interfaces */  
    12.   
    13.   s = getaddrinfo (NULL, port, &hints, &result);  
    14.   if (s != 0)  
    15.     {  
    16.       fprintf (stderr, "getaddrinfo: %s\n", gai_strerror (s));  
    17.       return -1;  
    18.     }  
    19.   
    20.   for (rp = result; rp != NULL; rp = rp->ai_next)  
    21.     {  
    22.       sfd = socket (rp->ai_family, rp->ai_socktype, rp->ai_protocol);  
    23.       if (sfd == -1)  
    24.         continue;  
    25.   
    26.       s = bind (sfd, rp->ai_addr, rp->ai_addrlen);  
    27.       if (s == 0)  
    28.         {  
    29.           /* We managed to bind successfully! */  
    30.           break;  
    31.         }  
    32.   
    33.       close (sfd);  
    34.     }  
    35.   
    36.   if (rp == NULL)  
    37.     {  
    38.       fprintf (stderr, "Could not bind\n");  
    39.       return -1;  
    40.     }  
    41.   
    42.   freeaddrinfo (result);  
    43.   
    44.   return sfd;  
    45. }  


    create_and_bind函数包含了一种可移植方式来获取IPv4或IPv6套接字的标准代码段。它接受一个port的字符串参数,port是从argv\[1\]中传入的。其中,getaddrinfo函数返回一群addrinfo到result,其中它们跟传入的hints参数是兼容的。 addrinfo结构体如下:

    C代码  收藏代码
    1. struct addrinfo  
    2. {  
    3.   int              ai_flags;  
    4.   int              ai_family;  
    5.   int              ai_socktype;  
    6.   int              ai_protocol;  
    7.   size_t           ai_addrlen;  
    8.   struct sockaddr *ai_addr;  
    9.   char            *ai_canonname;  
    10.   struct addrinfo *ai_next;  
    11. };  


    我们依次遍历这些结构体并用其来创建结构体,直到我们可以同时创建和绑定到socket。如果我们成功,create_and_bind() 会返回一个socket描述符。失败则返回 -1.

    接下来,我们写一个用来设置socket为非阻塞的函数。 make_socket_non_blocking() 设置 O_NONBLOCK 标志给传入的sfd描述符参数。
    C代码  收藏代码
    1. static int  
    2. make_socket_non_blocking (int sfd)  
    3. {  
    4.   int flags, s;  
    5.   
    6.   flags = fcntl (sfd, F_GETFL, 0);  
    7.   if (flags == -1)  
    8.     {  
    9.       perror ("fcntl");  
    10.       return -1;  
    11.     }  
    12.   
    13.   flags |= O_NONBLOCK;  
    14.   s = fcntl (sfd, F_SETFL, flags);  
    15.   if (s == -1)  
    16.     {  
    17.       perror ("fcntl");  
    18.       return -1;  
    19.     }  
    20.   
    21.   return 0;  
    22. }  


    接下来的main()函数中,它包含有一个事件循环。 下面是代码:

    C代码  收藏代码
    1. #define MAXEVENTS 64  
    2.   
    3. int  
    4. main (int argc, char *argv[])  
    5. {  
    6.   int sfd, s;  
    7.   int efd;  
    8.   struct epoll_event event;  
    9.   struct epoll_event *events;  
    10.   
    11.   if (argc != 2)  
    12.     {  
    13.       fprintf (stderr, "Usage: %s [port]\n", argv[0]);  
    14.       exit (EXIT_FAILURE);  
    15.     }  
    16.   
    17.   sfd = create_and_bind (argv[1]);  
    18.   if (sfd == -1)  
    19.     abort ();  
    20.   
    21.   s = make_socket_non_blocking (sfd);  
    22.   if (s == -1)  
    23.     abort ();  
    24.   
    25.   s = listen (sfd, SOMAXCONN);  
    26.   if (s == -1)  
    27.     {  
    28.       perror ("listen");  
    29.       abort ();  
    30.     }  
    31.   
    32.   efd = epoll_create1 (0);  
    33.   if (efd == -1)  
    34.     {  
    35.       perror ("epoll_create");  
    36.       abort ();  
    37.     }  
    38.   
    39.   event.data.fd = sfd;  
    40.   event.events = EPOLLIN | EPOLLET;  
    41.   s = epoll_ctl (efd, EPOLL_CTL_ADD, sfd, &event);  
    42.   if (s == -1)  
    43.     {  
    44.       perror ("epoll_ctl");  
    45.       abort ();  
    46.     }  
    47.   
    48.   /* Buffer where events are returned */  
    49.   events = calloc (MAXEVENTS, sizeof event);  
    50.   
    51.   /* The event loop */  
    52.   while (1)  
    53.     {  
    54.       int n, i;  
    55.   
    56.       n = epoll_wait (efd, events, MAXEVENTS, -1);  
    57.       for (i = 0; i < n; i++)  
    58.     {  
    59.       if ((events[i].events & EPOLLERR) ||  
    60.               (events[i].events & EPOLLHUP) ||  
    61.               (!(events[i].events & EPOLLIN)))  
    62.         {  
    63.               /* An error has occured on this fd, or the socket is not 
    64.                  ready for reading (why were we notified then?) */  
    65.           fprintf (stderr, "epoll error\n");  
    66.           close (events[i].data.fd);  
    67.           continue;  
    68.         }  
    69.   
    70.       else if (sfd == events[i].data.fd)  
    71.         {  
    72.               /* We have a notification on the listening socket, which 
    73.                  means one or more incoming connections. */  
    74.               while (1)  
    75.                 {  
    76.                   struct sockaddr in_addr;  
    77.                   socklen_t in_len;  
    78.                   int infd;  
    79.                   char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];  
    80.   
    81.                   in_len = sizeof in_addr;  
    82.                   infd = accept (sfd, &in_addr, &in_len);  
    83.                   if (infd == -1)  
    84.                     {  
    85.                       if ((errno == EAGAIN) ||  
    86.                           (errno == EWOULDBLOCK))  
    87.                         {  
    88.                           /* We have processed all incoming 
    89.                              connections. */  
    90.                           break;  
    91.                         }  
    92.                       else  
    93.                         {  
    94.                           perror ("accept");  
    95.                           break;  
    96.                         }  
    97.                     }  
    98.   
    99.                   s = getnameinfo (&in_addr, in_len,  
    100.                                    hbuf, sizeof hbuf,  
    101.                                    sbuf, sizeof sbuf,  
    102.                                    NI_NUMERICHOST | NI_NUMERICSERV);  
    103.                   if (s == 0)  
    104.                     {  
    105.                       printf("Accepted connection on descriptor %d "  
    106.                              "(host=%s, port=%s)\n", infd, hbuf, sbuf);  
    107.                     }  
    108.   
    109.                   /* Make the incoming socket non-blocking and add it to the 
    110.                      list of fds to monitor. */  
    111.                   s = make_socket_non_blocking (infd);  
    112.                   if (s == -1)  
    113.                     abort ();  
    114.   
    115.                   event.data.fd = infd;  
    116.                   event.events = EPOLLIN | EPOLLET;  
    117.                   s = epoll_ctl (efd, EPOLL_CTL_ADD, infd, &event);  
    118.                   if (s == -1)  
    119.                     {  
    120.                       perror ("epoll_ctl");  
    121.                       abort ();  
    122.                     }  
    123.                 }  
    124.               continue;  
    125.             }  
    126.           else  
    127.             {  
    128.               /* We have data on the fd waiting to be read. Read and 
    129.                  display it. We must read whatever data is available 
    130.                  completely, as we are running in edge-triggered mode 
    131.                  and won't get a notification again for the same 
    132.                  data. */  
    133.               int done = 0;  
    134.   
    135.               while (1)  
    136.                 {  
    137.                   ssize_t count;  
    138.                   char buf[512];  
    139.   
    140.                   count = read (events[i].data.fd, buf, sizeof buf);  
    141.                   if (count == -1)  
    142.                     {  
    143.                       /* If errno == EAGAIN, that means we have read all 
    144.                          data. So go back to the main loop. */  
    145.                       if (errno != EAGAIN)  
    146.                         {  
    147.                           perror ("read");  
    148.                           done = 1;  
    149.                         }  
    150.                       break;  
    151.                     }  
    152.                   else if (count == 0)  
    153.                     {  
    154.                       /* End of file. The remote has closed the 
    155.                          connection. */  
    156.                       done = 1;  
    157.                       break;  
    158.                     }  
    159.   
    160.                   /* Write the buffer to standard output */  
    161.                   s = write (1, buf, count);  
    162.                   if (s == -1)  
    163.                     {  
    164.                       perror ("write");  
    165.                       abort ();  
    166.                     }  
    167.                 }  
    168.   
    169.               if (done)  
    170.                 {  
    171.                   printf ("Closed connection on descriptor %d\n",  
    172.                           events[i].data.fd);  
    173.   
    174.                   /* Closing the descriptor will make epoll remove it 
    175.                      from the set of descriptors which are monitored. */  
    176.                   close (events[i].data.fd);  
    177.                 }  
    178.             }  
    179.         }  
    180.     }  
    181.   
    182.   free (events);  
    183.   
    184.   close (sfd);  
    185.   
    186.   return EXIT_SUCCESS;  
    187. }  


    关于main函数里就不多说了。

    下载 epoll-example.c 程序。
  • 相关阅读:
    Python中的memoryview
    Python常见陷阱
    特殊方法 之 len __repr__ __str__
    collections模块
    使用math中的hypot实现向量
    Ellipsis对象
    array
    标准库heapq的使用
    Mysql常用命令
    使用npm查看安装的包
  • 原文地址:https://www.cnblogs.com/lexus/p/2855594.html
Copyright © 2011-2022 走看看