2 * Copyright (c) 2004, 2005, 2007 Darren Tucker (dtucker at zip com au).
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 #if !defined(HAVE_POLL)
20 #include <sys/types.h>
22 #ifdef HAVE_SYS_SELECT_H
23 # include <sys/select.h>
32 * A minimal implementation of poll(2), built on top of select(2).
34 * Only supports POLLIN and POLLOUT flags in pfd.events, and POLLIN, POLLOUT
35 * and POLLERR flags in revents.
37 * Supports pfd.fd = -1 meaning "unused" although it's not standard.
41 poll(struct pollfd *fds, nfds_t nfds, int timeout)
44 int saved_errno, ret, fd, maxfd = 0;
45 fd_set *readfds = NULL, *writefds = NULL, *exceptfds = NULL;
47 struct timeval tv, *tvp = NULL;
49 for (i = 0; i < nfds; i++) {
51 if (fd >= FD_SETSIZE) {
55 maxfd = MAX(maxfd, fd);
58 nmemb = howmany(maxfd + 1 , NFDBITS);
59 if ((readfds = calloc(nmemb, sizeof(fd_mask))) == NULL ||
60 (writefds = calloc(nmemb, sizeof(fd_mask))) == NULL ||
61 (exceptfds = calloc(nmemb, sizeof(fd_mask))) == NULL) {
67 /* populate event bit vectors for the events we're interested in */
68 for (i = 0; i < nfds; i++) {
72 if (fds[i].events & POLLIN) {
74 FD_SET(fd, exceptfds);
76 if (fds[i].events & POLLOUT) {
78 FD_SET(fd, exceptfds);
82 /* poll timeout is msec, select is timeval (sec + usec) */
84 tv.tv_sec = timeout / 1000;
85 tv.tv_usec = (timeout % 1000) * 1000;
89 ret = select(maxfd + 1, readfds, writefds, exceptfds, tvp);
92 /* scan through select results and set poll() flags */
93 for (i = 0; i < nfds; i++) {
98 if (FD_ISSET(fd, readfds)) {
99 fds[i].revents |= POLLIN;
101 if (FD_ISSET(fd, writefds)) {
102 fds[i].revents |= POLLOUT;
104 if (FD_ISSET(fd, exceptfds)) {
105 fds[i].revents |= POLLERR;