two minor bugfixes.
[vde.git] / vde-2 / poll2select.c
blobfcf84b7c240fc7ce02188c196c80089bb6402a67
1 /*
2 * poll2select - convert poll() calls to select() calls
3 * Copyright 2005 Ludovico Gardenghi
4 * Licensed under the GPLv2
5 */
7 #include <config.h>
8 #include <sys/select.h>
9 #include <sys/time.h>
10 #include <sys/types.h>
11 #include <unistd.h>
12 #include <errno.h>
13 #include <syslog.h>
15 #include <consmgmt.h>
16 #include <vde.h>
18 #include "poll2select.h"
20 #ifndef MAX
21 #define MAX(x,y) ((x)>(y)?(x):(y))
22 #endif
24 static int prepare_select(struct pollfd *ufds, nfds_t nfds, int timeout,
25 struct timeval **pstimeout, int *maxfdp1, fd_set *rfds, fd_set *wfds, fd_set *efds)
27 register int i;
28 struct pollfd *currfd;
29 struct timeval *stimeout = *pstimeout;
32 * Conversion of information about file descriptors
35 *maxfdp1 = 0;
37 if ((nfds > 0) && (ufds == NULL))
39 errno = EFAULT;
40 return 0;
43 for (i = 0; i < nfds; i++)
45 currfd = &ufds[i];
47 if (currfd->fd < 0)
49 errno = EBADF;
50 return 0;
53 if (currfd->events & POLLIN)
54 FD_SET(currfd->fd, rfds);
55 if (currfd->events & POLLOUT)
56 FD_SET(currfd->fd, wfds);
57 if (currfd->events & POLLPRI)
58 FD_SET(currfd->fd, efds);
60 *maxfdp1 = MAX(*maxfdp1, currfd->fd);
63 (*maxfdp1)++;
66 * Conversion of information about timeout
69 if (timeout == 0)
71 if (stimeout == NULL)
73 errno = EINVAL;
74 return 0;
76 stimeout->tv_sec = 0;
77 stimeout->tv_usec = 0;
79 else if (timeout > 0)
81 if (stimeout == NULL)
83 errno = EINVAL;
84 return 0;
86 stimeout->tv_sec = timeout / 1000;
87 stimeout->tv_usec = (timeout % 1000) * 1000;
89 else // if (timeout < 0)
90 *pstimeout = NULL;
92 return 1;
95 static int convert_results(struct pollfd *ufds, int nfds,
96 fd_set *rfds, fd_set *wfds, fd_set *efds)
98 register int i;
99 struct pollfd *currfd;
100 int retval = 0;
102 for (i = 0; i < nfds; i++)
104 currfd = &ufds[i];
106 currfd->revents = 0;
108 if (FD_ISSET(currfd->fd, rfds))
109 currfd->revents |= POLLIN;
110 if (FD_ISSET(currfd->fd, wfds))
111 currfd->revents |= POLLOUT;
112 if (FD_ISSET(currfd->fd, efds))
113 currfd->revents |= POLLPRI;
115 if (currfd->revents != 0)
116 retval++;
119 return retval;
122 int poll2select(struct pollfd *ufds, nfds_t nfds, int timeout)
124 fd_set rfds, wfds, efds;
125 struct timeval stimeout;
126 struct timeval *pstimeout = &stimeout;
127 int maxfdp1;
128 int pretval, sretval, tretval;
130 FD_ZERO(&rfds);
131 FD_ZERO(&wfds);
132 FD_ZERO(&efds);
134 tretval = prepare_select(ufds, nfds, timeout, &pstimeout, &maxfdp1, &rfds, &wfds, &efds);
135 if (!tretval)
136 return -1;
138 sretval = select(maxfdp1, &rfds, &wfds, &efds, pstimeout);
139 if (sretval <= 0)
140 return sretval;
142 pretval = convert_results(ufds, nfds, &rfds, &wfds, &efds);
144 return pretval;