Created
April 9, 2013 08:20
-
-
Save mizzy/5343937 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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