Skip to content

Instantly share code, notes, and snippets.

@mizzy
Created April 9, 2013 08:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizzy/5343937 to your computer and use it in GitHub Desktop.
Save mizzy/5343937 to your computer and use it in GitHub Desktop.
int sock = socket(PF_INET, SOCK_STREAM);
bind(sock, addr);
listen(sock);
struct epoll_event ev;
struct epoll_event events[1024];
int epfd = epoll_create(1024);
ev.events = EPOLLIN;
ev.data.fd = sock;
epoll_ctl(epfd, EPOLL_CTL_ADD, sock, &ev);
while ( 1 ) {
int nfd = epoll_wait(epfd, events, 1024, -1);
for (i = 0; i < nfd; i++) {
if ( events[i].data.fd == sock ) {
int client = accept(sock, &addr);
ev.events = EPOLLIN;
ev.data.fd = client;
epoll_ctl(epfd, EPOLL_CTL_ADD, client, &ev);
}
else {
int client = events[i].data.fd;
int n = read(client, buffer, sizeof buffer);
if (n < 0) {
perror("read");
epoll_ctl(epfd, EPOLL_CTL_DEL, client, &ev);
close(client);
} else if (n == 0) {
epoll_ctl(epfd, EPOLL_CTL_DEL, client, &ev);
close(client);
} else {
write(client, buffer, n);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment