Skip to content

Instantly share code, notes, and snippets.

@aji
Created December 3, 2013 16:49
Show Gist options
  • Save aji/7772696 to your computer and use it in GitHub Desktop.
Save aji/7772696 to your computer and use it in GitHub Desktop.
#include <unistd.h>
#include <sys/time.h>
#include <sys/select.h>
#include <errno.h>
/* this function does not do much error checking. be warned! */
ssize_t read_timeout(int fd, char *buf, size_t len, int timeout)
{
ssize_t sz, rsz;
fd_set r;
struct timeval now, end, tv;
FD_ZERO(&r);
gettimeofday(&end, NULL);
end.tv_sec += timeout;
sz = 0;
for (;;) {
gettimeofday(&now, NULL);
if (!timercmp(&end, &now, >))
break;
timersub(&end, &now, &tv);
FD_SET(fd, &r);
if (select(fd+1, &r, NULL, NULL, &tv) < 0) {
if (errno == EAGAIN)
continue;
if (errno == EINTR)
break;
return -1;
}
if (FD_ISSET(fd, &r)) {
rsz = read(fd, buf, len);
if (rsz == 0)
break;
if (rsz < 0)
return rsz;
sz += rsz;
buf += rsz;
len -= rsz;
}
}
return sz;
}
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/select.h>
extern ssize_t read_timeout(int fd, char *buf, size_t len, int timeout);
int main(int argc, char *argv[])
{
char buf[301];
ssize_t sz;
sz = read_timeout(0, buf, 300, 5);
if (sz >= 0) buf[sz] = '\0';
printf("read %d bytes: %s", sz, buf);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment