Skip to content

Instantly share code, notes, and snippets.

@vamdt
Created July 18, 2018 05:22
Show Gist options
  • Save vamdt/78b014f81aab31de55fbaf745032d38b to your computer and use it in GitHub Desktop.
Save vamdt/78b014f81aab31de55fbaf745032d38b to your computer and use it in GitHub Desktop.
epoll api
#include <stdio.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <string.h>
int main() {
int epoll_fd = epoll_create1(0);
struct epoll_event event, events[5];
char read_buffer[11];
int running = 1, event_count, i;
ssize_t bytes_read;
if (epoll_fd == -1) {
fprintf(stderr, "Failed to create epoll fd!");
return 1;
}
event.events = EPOLLIN;
event.data.fd = 0;
if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, 0, &event)) {
fprintf(stderr, "Failed to add fd to epoll!");
close(epoll_fd);
return 1;
}
while(running) {
printf("Polling for input...\n");
event_count = epoll_wait(epoll_fd, events, 5, 30000);
printf("ready events count :%d\n",event_count);
for(i=0; i<event_count; i++) {
printf("reading fd %d, ", events[i].data.fd);
bytes_read = read(events[i].data.fd, read_buffer, 10);
printf("read bytes %d\n", bytes_read);
read_buffer[bytes_read]= '\0';
printf("read '%s' \n", read_buffer);
if (!strncmp(read_buffer, "quit\n", 5)) {
running = 0;
}
}
}
if (close(epoll_fd)) {
fprintf(stderr, "Failed to close epoll fd!");
return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment