Gerard-Meier

How to use epoll (simple)

May 15th, 2012
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. #include <cstdlib>
  2. #include <sys/epoll.h>
  3. #include <iostream>
  4.  
  5. #define MAXEVENTS 64
  6.  
  7. using namespace std;
  8.  
  9. string readLine(int fd) {
  10.     char in;
  11.     string buffer;
  12.  
  13.     // Read till the end, or a newline.
  14.     while(read(fd, &in, 1) > 0) {
  15.         buffer.push_back(in);
  16.  
  17.         if(in == '\n') {
  18.             break;
  19.         }
  20.     }
  21.  
  22.     return buffer;
  23. }
  24.  
  25.  
  26. int main(int argc, char** argv) {
  27.  
  28.     // Create the epoll FD:
  29.     int epollFd = epoll_create1(0);
  30.     if(epollFd == -1) {
  31.         cout << "Unable to create epoll instance." << endl;
  32.         return 1;
  33.     }
  34.  
  35.     // Let's read from the stdin:
  36.     epoll_event readEvent;
  37.     readEvent.data.fd = 0; // 0 = STDIN.
  38.     readEvent.events  = EPOLLIN | EPOLLET; // EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP
  39.  
  40.     // Attempt to add the event:
  41.     if(epoll_ctl(epollFd, EPOLL_CTL_ADD, readEvent.data.fd, &readEvent) == -1) {
  42.         cout << "Unable to add fd to epoll" << endl;
  43.         return 1;
  44.     }
  45.  
  46.     // Will hold all recent events:
  47.     epoll_event *newEvents = (struct epoll_event*) calloc (MAXEVENTS, sizeof readEvent);
  48.  
  49.     while(1) {
  50.  
  51.         cout << "Calling epoll wait." << endl;
  52.  
  53.         // Blocking call, will wait until an event occurs:
  54.         int eventCount = epoll_wait (epollFd, newEvents, MAXEVENTS, -1);
  55.  
  56.         // Iterate over all events:
  57.         for(int i = 0; i < eventCount; ++i) {
  58.             epoll_event& event = newEvents[i];
  59.  
  60.             cout << "Received some sort of event!" << endl;
  61.  
  62.             // Most scripts include this, I'm actually unsure why.
  63.             if ((event.events & EPOLLERR) || (event.events & EPOLLHUP) || (!(event.events & EPOLLIN))) {
  64.                 cout << "Some sort of broken socket? Closing said socket now." << endl;
  65.                 close (event.data.fd);
  66.             }
  67.  
  68.             // Read some data:
  69.             string line = readLine(event.data.fd);
  70.  
  71.             cout << "Data read: " << line;
  72.         }
  73.  
  74.     }
  75.  
  76.     return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment