Chinaunix首页 | 论坛 | 博客
  • 博客访问: 447246
  • 博文数量: 138
  • 博客积分: 4114
  • 博客等级: 上校
  • 技术积分: 1341
  • 用 户 组: 普通用户
  • 注册时间: 2007-10-14 20:41
文章分类

全部博文(138)

文章存档

2014年(1)

2013年(2)

2012年(78)

2011年(13)

2010年(34)

2009年(10)

我的朋友

分类: LINUX

2012-03-03 19:20:10

I think this is the best passages that tells u how to use epoll. enjoy it

excerpt from
https://banu.com/blog/2/how-to-use-epoll-a-complete-example-in-c/


Network servers are traditionally implemented using a separate process or thread per connection. For high performance applications that need to handle a very large number of clients simultaneously, this approach won't work well, because factors such as resource usage and context-switching time influence the ability to handle many clients at a time. An alternate method is to perform in a single thread, along with some readiness notification method which tells you when you can read or write more data on a socket.

This article is an introduction to Linux's epoll(7) facility, which is the best readiness notification facility in Linux. We will write sample code for a complete TCP server implementation in C. I assume you have C programming experience, know how to compile and run programs on Linux, and can read manpages of the various C functions that are used.

epoll was introduced in Linux 2.6, and is not available in other UNIX-like operating systems. It provides a facility similar to the select(2) and poll(2) functions:

  • select(2) can monitor up to FD_SETSIZE number of descriptors at a time, typically a small number determined at libc's compile time.
  • poll(2) doesn't have a fixed limit of descriptors it can monitor at a time, but apart from other things, even we have to perform a linear scan of all the passed descriptors every time to check readiness notification, which is O(n) and slow.

epoll has no such fixed limits, and does not perform any linear scans. Hence it is able to perform better and handle a larger number of events.

An epoll instance is created by epoll_create(2) or epoll_create1(2) (they take different arguments), which return an epoll instance. epoll_ctl(2) is used to add/remove descriptors to be watched on the epoll instance. To wait for events on the watched set, epoll_wait(2) is used, which blocks until events are available. Please see their manpages for more info.

When descriptors are added to an epoll instance, they can be added in two modes: level triggered and edge triggered. When you use level triggered mode, and data is available for reading, epoll_wait(2) will always return with ready events. If you don't read the data completely, and call epoll_wait(2) on the epoll instance watching the descriptor again, it will return again with a ready event because data is available. In edge triggered mode, you will only get a readiness notfication once. If you don't read the data fully, and call epoll_wait(2) on the epoll instance watching the descriptor again, it will block because the readiness event was already delivered.

The epoll event structure that you pass to epoll_ctl(2) is shown below. With every descriptor being watched, you can associate an integer or a pointer as user data.

  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. struct epoll_event
  9. {
  10.   __uint32_t events; /* Epoll events */
  11.   epoll_data_t data; /* User data variable */
  12. };
Let's write code now. We'll implement a tiny TCP server that prints everything sent to the socket on standard output. We'll begin by writing a function create_and_bind() which creates and binds a TCP socket:

  1. static int
  2. create_and_bind (char *port)
  3. {
  4.   struct addrinfo hints;
  5.   struct addrinfo *result, *rp;
  6.   int s, sfd;

  7.   memset (&hints, 0, sizeof (struct addrinfo));
  8.   hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */
  9.   hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */
  10.   hints.ai_flags = AI_PASSIVE; /* All interfaces */

  11.   s = getaddrinfo (NULL, port, &hints, &result);
  12.   if (s != 0)
  13.     {
  14.       fprintf (stderr, "getaddrinfo: %s\n", gai_strerror (s));
  15.       return -1;
  16.     }

  17.   for (rp = result; rp != NULL; rp = rp->ai_next)
  18.     {
  19.       sfd = socket (rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  20.       if (sfd == -1)
  21.         continue;

  22.       s = bind (sfd, rp->ai_addr, rp->ai_addrlen);
  23.       if (s == 0)
  24.         {
  25.           /* We managed to bind */
  26.           break;
  27.         }

  28.       close (sfd);
  29.     }

  30.   if (rp == NULL)
  31.     {
  32.       fprintf (stderr, "Could not bind\n");
  33.       return -1;
  34.     }

  35.   freeaddrinfo (result);

  36.   return sfd;
  37. }
create_and_bind() contains a standard code block for a portable way of getting a IPv4 or IPv6 socket. It accepts a port argument as a string, where argv[1] can be passed. The getaddrinfo(3) function returns a bunch of addrinfo structures in result, which are compatible with the hints passed in the hints argument. The addrinfo struct looks like this:

  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. };

We walk through the structures one by one and try creating sockets using them, until we are able to both create and bind a socket. If we were successful, create_and_bind() returns the socket descriptor. If unsuccessful, it returns -1.

Next, let's write a function to make a socket non-blocking. make_socket_non_blocking() sets the O_NONBLOCK flag on the descriptor passed in the sfd argument:

  1. static int
  2. make_socket_non_blocking (int sfd)
  3. {
  4.   int flags, s;

  5.   flags = fcntl (sfd, F_GETFL, 0);
  6.   if (flags == -1)
  7.     {
  8.       perror ("fcntl");
  9.       return -1;
  10.     }

  11.   flags |= O_NONBLOCK;
  12.   s = fcntl (sfd, F_SETFL, flags);
  13.   if (s == -1)
  14.     {
  15.       perror ("fcntl");
  16.       return -1;
  17.     }

  18.   return 0;
  19. }

Now, on to the main() function of the program which contains the event loop. This is the bulk of the program:

  1. #define MAXEVENTS 64

  2. int
  3. main (int argc, char *argv[])
  4. {
  5.   int sfd, s;
  6.   int efd;
  7.   struct epoll_event event;
  8.   struct epoll_event *events;

  9.   if (argc != 2)
  10.     {
  11.       fprintf (stderr, "Usage: %s [port]\n", argv[0]);
  12.       exit (EXIT_FAILURE);
  13.     }

  14.   sfd = create_and_bind (argv[1]);
  15.   if (sfd == -1)
  16.     abort ();

  17.   s = make_socket_non_blocking (sfd);
  18.   if (s == -1)
  19.     abort ();

  20.   s = listen (sfd, SOMAXCONN);
  21.   if (s == -1)
  22.     {
  23.       perror ("listen");
  24.       abort ();
  25.     }

  26.   efd = epoll_create1 (0);
  27.   if (efd == -1)
  28.     {
  29.       perror ("epoll_create");
  30.       abort ();
  31.     }

  32.   event.data.fd = sfd;
  33.   event.events = EPOLLIN | EPOLLET;
  34.   s = epoll_ctl (efd, EPOLL_CTL_ADD, sfd, &event);
  35.   if (s == -1)
  36.     {
  37.       perror ("epoll_ctl");
  38.       abort ();
  39.     }

  40.   /* Buffer where events are returned */
  41.   events = calloc (MAXEVENTS, sizeof event);

  42.   /* The event loop */
  43.   while (1)
  44.     {
  45.       int n, i;

  46.       n = epoll_wait (efd, events, MAXEVENTS, -1);
  47.       for (i = 0; i < n; i++)
  48.     {
  49.      if ((events[i].events & EPOLLERR) ||
  50.               (events[i].events & EPOLLHUP) ||
  51.               (!(events[i].events & EPOLLIN)))
  52.      {
  53.               /* An error has occured on this fd, or the socket is not
  54.                  ready for reading (why were we notified then?) */
  55.      fprintf (stderr, "epoll error\n");
  56.      close (events[i].data.fd);
  57.      continue;
  58.      }

  59.      else if (sfd == events[i].data.fd)
  60.      {
  61.               /* We have a notification on the listening socket, which
  62.                  means one or more incoming connections. */
  63.               while (1)
  64.                 {
  65.                   struct sockaddr in_addr;
  66.                   socklen_t in_len;
  67.                   int infd;
  68.                   char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];

  69.                   in_len = sizeof in_addr;
  70.                   infd = accept (sfd, &in_addr, &in_len);
  71.                   if (infd == -1)
  72.                     {
  73.                       if ((errno == EAGAIN) ||
  74.                           (errno == EWOULDBLOCK))
  75.                         {
  76.                           /* We have processed all incoming
  77.                              connections. */
  78.                           break;
  79.                         }
  80.                       else
  81.                         {
  82.                           perror ("accept");
  83.                           break;
  84.                         }
  85.                     }

  86.                   s = getnameinfo (&in_addr, in_len,
  87.                                    hbuf, sizeof hbuf,
  88.                                    sbuf, sizeof sbuf,
  89.                                    NI_NUMERICHOST | NI_NUMERICSERV);
  90.                   if (s == 0)
  91.                     {
  92.                       printf("Accepted connection on descriptor %d "
  93.                              "(host=%s, port=%s)\n", infd, hbuf, sbuf);
  94.                     }

  95.                   /* Make the incoming socket non-blocking and add it to the
  96.                      list of fds to monitor. */
  97.                   s = make_socket_non_blocking (infd);
  98.                   if (s == -1)
  99.                     abort ();

  100.                   event.data.fd = infd;
  101.                   event.events = EPOLLIN | EPOLLET;
  102.                   s = epoll_ctl (efd, EPOLL_CTL_ADD, infd, &event);
  103.                   if (s == -1)
  104.                     {
  105.                       perror ("epoll_ctl");
  106.                       abort ();
  107.                     }
  108.                 }
  109.               continue;
  110.             }
  111.           else
  112.             {
  113.               /* We have data on the fd waiting to be read. Read and
  114.                  display it. We must read whatever data is available
  115.                  completely, as we are running in edge-triggered mode
  116.                  and won't get a notification again for the same
  117.                  data. */
  118.               int done = 0;

  119.               while (1)
  120.                 {
  121.                   ssize_t count;
  122.                   char buf[512];

  123.                   count = read (events[i].data.fd, buf, sizeof buf);
  124.                   if (count == -1)
  125.                     {
  126.                       /* If errno == EAGAIN, that means we have read all
  127.                          data. So go back to the main loop. */
  128.                       if (errno != EAGAIN)
  129.                         {
  130.                           perror ("read");
  131.                           done = 1;
  132.                         }
  133.                       break;
  134.                     }
  135.                   else if (count == 0)
  136.                     {
  137.                       /* End of file. The remote has closed the
  138.                          connection. */
  139.                       done = 1;
  140.                       break;
  141.                     }

  142.                   /* Write the buffer to standard output */
  143.                   s = write (1, buf, count);
  144.                   if (s == -1)
  145.                     {
  146.                       perror ("write");
  147.                       abort ();
  148.                     }
  149.                 }

  150.               if (done)
  151.                 {
  152.                   printf ("Closed connection on descriptor %d\n",
  153.                           events[i].data.fd);

  154.                   /* Closing the descriptor will make epoll remove it
  155.                      from the set of descriptors which are monitored. */
  156.                   close (events[i].data.fd);
  157.                 }
  158.             }
  159.         }
  160.     }

  161.   free (events);

  162.   close (sfd);

  163.   return EXIT_SUCCESS;
  164. }

main() first calls create_and_bind() which sets up the socket. It then makes the socket non-blocking, and then calls listen(2). It then creates an epoll instance in efd, to which it adds the listening socket sfd to watch for input events in an edge-triggered mode.

The outer while loop is the main events loop. It calls epoll_wait(2), where the thread remains blocked waiting for events. When events are available, epoll_wait(2) returns the events in the events argument, which is a bunch of epoll_event structures.

The epoll instance in efd is continuously updated in the event loop when we add new incoming connections to watch, and remove existing connections when they die.

When events are available, they can be of three types:

  • Errors: When an error condition occurs, or the event is not a notification about data available for reading, we simply close the associated descriptor. Closing the descriptor automatically removes it from the watched set of epoll instance efd.
  • New connections: When the listening descriptor sfd is ready for reading, it means one or more new connections have arrived. While there are new connections, accept(2) the connections, print a message about it, make the incoming socket non-blocking and add it to the watched set of epoll instance efd.
  • Client data: When data is available for reading on any of the client descriptors, we use read(2) to read the data in pieces of 512 bytes in an inner while loop. This is because we have to read all the data that is available now, as we won't get further events about it as the descriptor is watched in edge-triggered mode. The data which is read is written to stdout (fd=1) using write(2). If read(2) returns 0, it means an EOF and we can close the client's connection. If -1 is returned, and errno is set to EAGAIN, it means that all data for this event was read, and we can go back to the main loop.

That's that. It goes around and around in a loop, adding and removing descriptors in the watched set.

Download the epoll-example.c program.

Update1: Level and edge triggered definitions were erroneously reversed (though the code was correct). It was noticed by Reddit user . The article has been corrected now. I should have proof-read it before posting. Apologies, and thank you for pointing out the mistake. :)

Update2: The code has been modified to run accept(2) until it says it would block, so that if multiple connections have arrived, we accept all of them. It was noticed by Reddit user . Thank you for the comments. :)

阅读(438) | 评论(0) | 转发(0) |
0

上一篇:kvm virt-manager

下一篇:gdb nginx

给主人留下些什么吧!~~