xnanosleep: Rewrite to use new dtotimespec module.
[gnulib.git] / lib / pselect.c
1 /* pselect - synchronous I/O multiplexing
2
3    Copyright 2011 Free Software Foundation, Inc.
4
5    This file is part of gnulib.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2, or (at your option)
10    any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License along
18    with this program; if not, write to the Free Software Foundation,
19    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
20
21 /* written by Paul Eggert */
22
23 #include <config.h>
24
25 #include <sys/select.h>
26
27 #include <errno.h>
28 #include <signal.h>
29
30 #undef pselect
31
32 /* Examine the size-NFDS file descriptor sets in RFDS, WFDS, and XFDS
33    to see whether some of their descriptors are ready for reading,
34    ready for writing, or have exceptions pending.  Wait for at most
35    TIMEOUT seconds, and use signal mask SIGMASK while waiting.  A null
36    pointer parameter stands for no descriptors, an infinite timeout,
37    or an unaffected signal mask.  */
38
39 int
40 rpl_pselect (int nfds, fd_set *restrict rfds,
41              fd_set *restrict wfds, fd_set *restrict xfds,
42              struct timespec const *restrict timeout,
43              sigset_t const *restrict sigmask)
44 {
45   int select_result;
46   sigset_t origmask;
47   struct timeval tv, *tvp;
48
49   if (timeout)
50     {
51       if (! (0 <= timeout->tv_nsec && timeout->tv_nsec < 1000000000))
52         {
53           errno = EINVAL;
54           return -1;
55         }
56
57       tv.tv_sec = timeout->tv_sec;
58       tv.tv_usec = (timeout->tv_nsec + 999) / 1000;
59       tvp = &tv;
60     }
61   else
62     tvp = NULL;
63
64   /* Signal mask munging should be atomic, but this is the best we can
65      do in this emulation.  */
66   if (sigmask)
67     sigprocmask (SIG_SETMASK, sigmask, &origmask);
68
69   select_result = select (nfds, rfds, wfds, xfds, tvp);
70
71   if (sigmask)
72     {
73       int select_errno = errno;
74       sigprocmask (SIG_SETMASK, &origmask, NULL);
75       errno = select_errno;
76     }
77
78   return select_result;
79 }