Skip to content

Commit

Permalink
use poll() instead of select()
Browse files Browse the repository at this point in the history
poll() is much nicer and more efficient API than select(), additionally
it doesn't require bitsets of 4096 bits which need to be initialized before
each call, improving CPU load and, best of all: ain't prone to stack
overflow should the user decide to change his OS's fd limit above 4096 and
having a fd above that number in use.

fixes rofl0r#13
closes rofl0r#16
  • Loading branch information
rofl0r committed Oct 24, 2020
1 parent 1fff3cc commit 3155785
Showing 1 changed file with 9 additions and 13 deletions.
22 changes: 9 additions & 13 deletions sockssrv.c
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
#include <sys/select.h>
#include <poll.h>
#include <arpa/inet.h>
#include <errno.h>
#include <limits.h>
Expand Down Expand Up @@ -245,29 +245,25 @@ static void send_error(int fd, enum errorcode ec) {
}

static void copyloop(int fd1, int fd2) {
int maxfd = fd2;
if(fd1 > fd2) maxfd = fd1;
fd_set fdsc, fds;
FD_ZERO(&fdsc);
FD_SET(fd1, &fdsc);
FD_SET(fd2, &fdsc);
struct pollfd fds[2] = {
[0] = {.fd = fd1, .events = POLLIN},
[1] = {.fd = fd2, .events = POLLIN},
};

while(1) {
memcpy(&fds, &fdsc, sizeof(fds));
/* inactive connections are reaped after 15 min to free resources.
usually programs send keep-alive packets so this should only happen
when a connection is really unused. */
struct timeval timeout = {.tv_sec = 60*15, .tv_usec = 0};
switch(select(maxfd+1, &fds, 0, 0, &timeout)) {
switch(poll(fds, 2, 60*15*1000)) {
case 0:
send_error(fd1, EC_TTL_EXPIRED);
return;
case -1:
if(errno == EINTR) continue;
else perror("select");
if(errno == EINTR || errno == EAGAIN) continue;
else perror("poll");
return;
}
int infd = FD_ISSET(fd1, &fds) ? fd1 : fd2;
int infd = (fds[0].revents & POLLIN) ? fd1 : fd2;
int outfd = infd == fd2 ? fd1 : fd2;
char buf[1024];
ssize_t sent = 0, n = read(infd, buf, sizeof buf);
Expand Down

0 comments on commit 3155785

Please sign in to comment.