[__APPLE__]: Include <mach/machine.h> and <mach-o/arch.h>.
[coreutils.git] / lib / nanosleep.c
blob2f91c31d83be691c91840697252c020e7bd66758
1 /* Provide a replacement for the POSIX nanosleep function.
2 Copyright (C) 1999, 2000, 2002, 2004 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
7 any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* written by Jim Meyering */
20 #include <config.h>
22 /* Undefine nanosleep here so any prototype is not redefined to be a
23 prototype for rpl_nanosleep. (they'd conflict e.g., on alpha-dec-osf3.2) */
24 #undef nanosleep
26 #include <stdbool.h>
27 #include <stdio.h>
28 #include <sys/types.h>
29 #include <signal.h>
31 #include <errno.h>
33 #if HAVE_UNISTD_H
34 # include <unistd.h>
35 #endif
37 /* Some systems (MSDOS) don't have SIGCONT.
38 Using SIGTERM here turns the signal-handling code below
39 into a no-op on such systems. */
40 #ifndef SIGCONT
41 # define SIGCONT SIGTERM
42 #endif
44 #include "timespec.h"
46 static sig_atomic_t volatile suspended;
48 /* Handle SIGCONT. */
50 static void
51 sighandler (int sig)
53 suspended = 1;
56 /* FIXME: comment */
58 static void
59 my_usleep (const struct timespec *ts_delay)
61 struct timeval tv_delay;
62 tv_delay.tv_sec = ts_delay->tv_sec;
63 tv_delay.tv_usec = (ts_delay->tv_nsec + 999) / 1000;
64 if (tv_delay.tv_usec == 1000000)
66 tv_delay.tv_sec++;
67 tv_delay.tv_usec = 0;
69 select (0, (void *) 0, (void *) 0, (void *) 0, &tv_delay);
72 /* FIXME: comment */
74 int
75 rpl_nanosleep (const struct timespec *requested_delay,
76 struct timespec *remaining_delay)
78 static bool initialized;
80 #ifdef SA_NOCLDSTOP
81 struct sigaction oldact, newact;
82 #endif
84 suspended = 0;
86 /* set up sig handler */
87 if (! initialized)
89 #ifdef SA_NOCLDSTOP
90 newact.sa_handler = sighandler;
91 sigemptyset (&newact.sa_mask);
92 newact.sa_flags = 0;
94 sigaction (SIGCONT, NULL, &oldact);
95 if (oldact.sa_handler != SIG_IGN)
96 sigaction (SIGCONT, &newact, NULL);
97 #else
98 if (signal (SIGCONT, SIG_IGN) != SIG_IGN)
99 signal (SIGCONT, sighandler);
100 #endif
101 initialized = true;
104 my_usleep (requested_delay);
106 if (suspended)
108 /* Calculate time remaining. */
109 /* FIXME: the code in sleep doesn't use this, so there's no
110 rush to implement it. */
112 errno = EINTR;
115 /* FIXME: Restore sig handler? */
117 return suspended;