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