Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdlib>
- #include <sys/epoll.h>
- #include <iostream>
- #define MAXEVENTS 64
- using namespace std;
- string readLine(int fd) {
- char in;
- string buffer;
- // Read till the end, or a newline.
- while(read(fd, &in, 1) > 0) {
- buffer.push_back(in);
- if(in == '\n') {
- break;
- }
- }
- return buffer;
- }
- int main(int argc, char** argv) {
- // Create the epoll FD:
- int epollFd = epoll_create1(0);
- if(epollFd == -1) {
- cout << "Unable to create epoll instance." << endl;
- return 1;
- }
- // Let's read from the stdin:
- epoll_event readEvent;
- readEvent.data.fd = 0; // 0 = STDIN.
- readEvent.events = EPOLLIN | EPOLLET; // EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP
- // Attempt to add the event:
- if(epoll_ctl(epollFd, EPOLL_CTL_ADD, readEvent.data.fd, &readEvent) == -1) {
- cout << "Unable to add fd to epoll" << endl;
- return 1;
- }
- // Will hold all recent events:
- epoll_event *newEvents = (struct epoll_event*) calloc (MAXEVENTS, sizeof readEvent);
- while(1) {
- cout << "Calling epoll wait." << endl;
- // Blocking call, will wait until an event occurs:
- int eventCount = epoll_wait (epollFd, newEvents, MAXEVENTS, -1);
- // Iterate over all events:
- for(int i = 0; i < eventCount; ++i) {
- epoll_event& event = newEvents[i];
- cout << "Received some sort of event!" << endl;
- // Most scripts include this, I'm actually unsure why.
- if ((event.events & EPOLLERR) || (event.events & EPOLLHUP) || (!(event.events & EPOLLIN))) {
- cout << "Some sort of broken socket? Closing said socket now." << endl;
- close (event.data.fd);
- }
- // Read some data:
- string line = readLine(event.data.fd);
- cout << "Data read: " << line;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment