Skip to content

Instantly share code, notes, and snippets.

@mrexmelle
Created January 10, 2019 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrexmelle/edbfc307afe0fcdd8d84b8923b00cef8 to your computer and use it in GitHub Desktop.
Save mrexmelle/edbfc307afe0fcdd8d84b8923b00cef8 to your computer and use it in GitHub Desktop.
epoll simple demonstration
// compile: gcc main_epoll.c -o main_epoll -std=c99
// run: ./main_epoll
// environment: Linux
#define MAX_EVENTS 5
#define READ_SIZE 5
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/epoll.h>
static int exit=0;
// signal callback
void sigint_handler(int signum)
{
if(signum==SIGINT)
{
printf("\nSIGINT triggered\n");
exit=1;
}
}
int main(int argc, char * argv[])
{
// register signal handler
signal(SIGINT, sigint_handler);
// init epoll structs
struct epoll_event config;
struct epoll_event events[MAX_EVENTS];
// create buffer
char buffer[READ_SIZE+1];
// init epoll
int efd=epoll_create1(0);
// check epoll creation status
if(efd==-1)
{
perror("epoll_create1");
return 1;
}
// setup epoll configurations: level-triggered, fd is stdin
config.events=EPOLLIN;
config.data.fd=0;
int err=epoll_ctl(efd, EPOLL_CTL_ADD, 0, &config);
if(err!=0)
{
perror("epoll_ctl");
close(efd);
return 2;
}
// start the loop
while(exit==0)
{
// poll events, timeout is 30000 millisec
int count=epoll_wait(efd, events, MAX_EVENTS, 30000);
printf("\nEvent count: %d\n", count);
for(int i=0; i<count; i++)
{
// read the buffer
int bytes_read=read(events[i].data.fd, buffer, READ_SIZE);
printf("\nBytes read: %d...\n", bytes_read);
// set null-terminator for display purpose
buffer[bytes_read]='\0';
printf("\nBuffer content: %s\n", buffer);
}
// prepare if sigint is raised at this point
if(exit==1) { break; }
}
// cleanup epoll's fd
close(efd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment