Last active
February 17, 2018 05:15
-
-
Save tjhv/5f317d795dea2457e60c825b2ece6343 to your computer and use it in GitHub Desktop.
Select() with callbacks per event
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
#include <sys/select.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
void fd_set_v2(unsigned int fd, | |
fd_set *fds, | |
unsigned int *max_fd) | |
{ | |
if(!(fds && max_fd)) return; | |
FD_SET(fd, fds); | |
if(fd > *max_fd) | |
*max_fd = fd; | |
} | |
void fd_clr_v2(unsigned int fd, | |
fd_set *fds, | |
unsigned int *max_fd) | |
{ | |
if(!(fds && max_fd)) return; | |
FD_CLR(fd, fds); | |
if(fd == *max_fd) | |
for(; !FD_ISSET(*max_fd, fds); *max_fd--); | |
} | |
void select_v2(unsigned int nfds, | |
fd_set *readfds, | |
fd_set *writefds, | |
fd_set *exceptfds, | |
unsigned int timeout_ms, | |
select_cb_t callback) | |
{ | |
struct timeval ttl; | |
if(timeout_ms != 0) | |
{ | |
ttl.tv_sec = timeout_ms / 1000; | |
ttl.tv_usec = (timeout_ms - ((timeout_ms / 1000) * 1000)) * 1000; | |
} | |
else | |
{ | |
ttl = NULL; | |
} | |
int rv = select(nfds + 1, readfds, writefds, exceptfds, &ttl); | |
if(rv < 0) | |
{ | |
perror("select()"); return; | |
} | |
if(rv == 0) | |
{ | |
printf("select(): timeout.\n"); return; | |
} | |
int rdyfds = rv; | |
for(unsigned int i = 0; i < nfds && rdyfds > 0; i++) | |
{ | |
fd_set *cbset = NULL; | |
if(FD_ISSET(i, readfds)) | |
cbset = readfds; | |
else if(FD_ISSET(i, writefds)) | |
cbset = writefds; | |
else if(FD_ISSET(i, exceptfds)) | |
cbset = exceptfds; | |
if(cbset) | |
{ | |
--rdyfds; | |
if(callback) | |
callback(i, cbset); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment