]> git.sesse.net Git - vlc/blob - src/network/poll.c
poll() replacement
[vlc] / src / network / poll.c
1 /*****************************************************************************
2  * poll.c: I/O event multiplexing
3  *****************************************************************************
4  * Copyright © 2007 Rémi Denis-Courmont
5  * $Id$
6  *
7  * Author: Rémi Denis-Courmont
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 #include <vlc/vlc.h>
25
26 #ifndef HAVE_POLL
27 #include <string.h>
28 #include <stdlib.h>
29 #include <vlc_network.h>
30
31 int poll (struct pollfd *fds, unsigned nfds, int timeout)
32 {
33     fd_set rdset, wrset, exset;
34     struct timeval tv = { 0, 0 };
35     int val = -1;
36
37
38     FD_ZERO (&rdset);
39     FD_ZERO (&wrset);
40     FD_ZERO (&exset);
41     for (unsigned i = 0; i < nfds; i++)
42     {
43         int fd = fds[i].fd;
44         if (val < fd)
45             val = fd;
46
47         /* I assume the OS has a solution select overflow if it does not have
48          * poll(). If it did not, we are screwed anyway. */
49         if (fds[i].events & POLLIN)
50             FD_SET (fd, &rdset);
51         if (fds[i].events & POLLOUT)
52             FD_SET (fd, &wrset);
53         if (fds[i].events & POLLPRI)
54             FD_SET (fd, &exset);
55     }
56
57     if (timeout >= 0)
58     {
59         div_t d = div (timeout, 1000);
60         tv.tv_sec = d.quot;
61         tv.tv_usec = d.rem * 1000;
62     }
63
64     val = select (val + 1, &rdset, &wrset, NULL,
65                   (timeout >= 0) ? &tv : NULL);
66     if (val == -1)
67         return -1;
68
69     for (unsigned i = 0; i < nfds; i++)
70     {
71         int fd = fds[i].fd;
72         fds[i].revents = (FD_ISSET (fds[i].fd, &rdset) ? POLLIN : 0)
73                        | (FD_ISSET (fds[i].fd, &wrset) ? POLLOUT : 0)
74                        | (FD_ISSET (fds[i].fd, &exset) ? POLLPRI : 0);
75     }
76     return val;
77 }
78 #endif /* !HAVE_POLL */