#include <sys_defs.h>
#include <sys/time.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#ifdef USE_SYSV_POLL
#include <poll.h>
#endif
#ifdef USE_SYS_SELECT_H
#include <sys/select.h>
#endif
#include <msg.h>
#include <iostuff.h>
int read_wait(int fd, int timeout)
{
#ifndef USE_SYSV_POLL
fd_set read_fds;
fd_set except_fds;
struct timeval tv;
struct timeval *tp;
if (FD_SETSIZE <= fd)
msg_panic("descriptor %d does not fit FD_SETSIZE %d", fd, FD_SETSIZE);
FD_ZERO(&read_fds);
FD_SET(fd, &read_fds);
FD_ZERO(&except_fds);
FD_SET(fd, &except_fds);
if (timeout >= 0) {
tv.tv_usec = 0;
tv.tv_sec = timeout;
tp = &tv;
} else {
tp = 0;
}
for (;;) {
switch (select(fd + 1, &read_fds, (fd_set *) 0, &except_fds, tp)) {
case -1:
if (errno != EINTR)
msg_fatal("select: %m");
continue;
case 0:
errno = ETIMEDOUT;
return (-1);
default:
return (0);
}
}
#else
struct pollfd pollfd;
#define WAIT_FOR_EVENT (-1)
pollfd.fd = fd;
pollfd.events = POLLIN;
for (;;) {
switch (poll(&pollfd, 1, timeout < 0 ?
WAIT_FOR_EVENT : timeout * 1000)) {
case -1:
if (errno != EINTR)
msg_fatal("poll: %m");
continue;
case 0:
errno = ETIMEDOUT;
return (-1);
default:
if (pollfd.revents & POLLNVAL)
msg_fatal("poll: %m");
return (0);
}
}
#endif
}
#ifdef __APPLE_OS_X_SERVER__
int read_wait_no_poll(int fd, int timeout)
{
fd_set read_fds;
fd_set except_fds;
struct timeval tv;
struct timeval *tp;
if (FD_SETSIZE <= fd)
msg_panic("descriptor %d does not fit FD_SETSIZE %d", fd, FD_SETSIZE);
FD_ZERO(&read_fds);
FD_SET(fd, &read_fds);
FD_ZERO(&except_fds);
FD_SET(fd, &except_fds);
if (timeout >= 0) {
tv.tv_usec = 0;
tv.tv_sec = timeout;
tp = &tv;
} else {
tp = 0;
}
for (;;) {
switch (select(fd + 1, &read_fds, (fd_set *) 0, &except_fds, tp)) {
case -1:
if (errno != EINTR)
msg_fatal("select: %m");
continue;
case 0:
errno = ETIMEDOUT;
return (-1);
default:
return (0);
}
}
}
#endif