In 2014, I think we can stop trying to outsmart the compiler. Remove
[vde.git] / vde-2 / src / common / poll.c
blobc471304290f2bd887c80fd5df6112a3bbb5a6b36
1 /*
2 * poll2select - convert poll() calls to select() calls
3 * Copyright 2005 Ludovico Gardenghi
4 * Licensed under the GPLv2
5 */
7 #include <sys/select.h>
8 #include <sys/time.h>
9 #include <sys/types.h>
10 #include <unistd.h>
11 #include <errno.h>
12 #include <syslog.h>
14 #include <config.h>
15 #include <vde.h>
16 #include <vdecommon.h>
18 #ifndef MAX
19 #define MAX(x,y) ((x)>(y)?(x):(y))
20 #endif
22 static int prepare_select(struct pollfd *ufds, nfds_t nfds, int timeout,
23 struct timeval **pstimeout, int *maxfdp1, fd_set *rfds, fd_set *wfds, fd_set *efds)
25 int i;
26 struct pollfd *currfd;
27 struct timeval *stimeout = *pstimeout;
30 * Conversion of information about file descriptors
33 *maxfdp1 = 0;
35 if ((nfds > 0) && (ufds == NULL))
37 errno = EFAULT;
38 return 0;
41 for (i = 0; i < nfds; i++)
43 currfd = &ufds[i];
45 if (currfd->fd < 0)
47 errno = EBADF;
48 return 0;
51 if (currfd->events & POLLIN)
52 FD_SET(currfd->fd, rfds);
53 if (currfd->events & POLLOUT)
54 FD_SET(currfd->fd, wfds);
55 if (currfd->events & POLLPRI)
56 FD_SET(currfd->fd, efds);
58 *maxfdp1 = MAX(*maxfdp1, currfd->fd);
61 (*maxfdp1)++;
64 * Conversion of information about timeout
67 if (timeout == 0)
69 if (stimeout == NULL)
71 errno = EINVAL;
72 return 0;
74 stimeout->tv_sec = 0;
75 stimeout->tv_usec = 0;
77 else if (timeout > 0)
79 if (stimeout == NULL)
81 errno = EINVAL;
82 return 0;
84 stimeout->tv_sec = timeout / 1000;
85 stimeout->tv_usec = (timeout % 1000) * 1000;
87 else // if (timeout < 0)
88 *pstimeout = NULL;
90 return 1;
93 static int convert_results(struct pollfd *ufds, int nfds,
94 fd_set *rfds, fd_set *wfds, fd_set *efds)
96 int i;
97 struct pollfd *currfd;
98 int retval = 0;
100 for (i = 0; i < nfds; i++)
102 currfd = &ufds[i];
104 currfd->revents = 0;
106 if (FD_ISSET(currfd->fd, rfds))
107 currfd->revents |= POLLIN;
108 if (FD_ISSET(currfd->fd, wfds))
109 currfd->revents |= POLLOUT;
110 if (FD_ISSET(currfd->fd, efds))
111 currfd->revents |= POLLPRI;
113 if (currfd->revents != 0)
114 retval++;
117 return retval;
120 int vde_poll(struct pollfd *ufds, nfds_t nfds, int timeout)
122 fd_set rfds, wfds, efds;
123 struct timeval stimeout;
124 struct timeval *pstimeout = &stimeout;
125 int maxfdp1;
126 int pretval, sretval, tretval;
128 FD_ZERO(&rfds);
129 FD_ZERO(&wfds);
130 FD_ZERO(&efds);
132 tretval = prepare_select(ufds, nfds, timeout, &pstimeout, &maxfdp1, &rfds, &wfds, &efds);
133 if (!tretval)
134 return -1;
136 sretval = select(maxfdp1, &rfds, &wfds, &efds, pstimeout);
137 if (sretval <= 0)
138 return sretval;
140 pretval = convert_results(ufds, nfds, &rfds, &wfds, &efds);
142 return pretval;