*** empty log message ***
[gnulib.git] / lib / nanosleep.c
1 /* Provide a replacement for the POSIX nanosleep function.
2    Copyright (C) 1999 Free Software Foundation, Inc.
3
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.
8
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.
13
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.  */
17
18 /* written by Jim Meyering */
19
20 #include <config.h>
21 #include <stdio.h>
22 #include <sys/types.h>
23 #include <signal.h>
24
25 #if HAVE_UNISTD_H
26 # include <unistd.h>
27 #endif
28
29 #include <time.h>
30 /* FIXME: is including both like this kosher?  */
31 #include <sys/time.h>
32
33 static int suspended;
34
35 /* Handle SIGCONT. */
36
37 static void
38 sighandler (int sig)
39 {
40 #ifdef SA_INTERRUPT
41   struct sigaction sigact;
42
43   sigact.sa_handler = SIG_DFL;
44   sigemptyset (&sigact.sa_mask);
45   sigact.sa_flags = 0;
46   sigaction (sig, &sigact, NULL);
47 #else
48   signal (sig, SIG_DFL);
49 #endif
50
51   suspended = 1;
52   kill (getpid (), sig);
53 }
54
55 /* Sleep for USEC microseconds. */
56
57 static void
58 my_usleep (const struct timespec *ts_delay)
59 {
60   struct timeval tv_delay;
61   tv_delay.tv_sec = ts_delay->tv_sec;
62   tv_delay.tv_usec = 1000 * ts_delay->tv_nsec;
63   select (0, (void *) 0, (void *) 0, (void *) 0, &tv_delay);
64 }
65
66 int
67 nanosleep (const struct timespec *requested_delay,
68            struct timespec *remaining_delay)
69 {
70 #ifdef SA_INTERRUPT
71   struct sigaction oldact, newact;
72 #endif
73
74   suspended = 0;
75
76   /* set up sig handler -- but maybe only do this the first time?  */
77 #ifdef SA_INTERRUPT
78   newact.sa_handler = sighandler;
79   sigemptyset (&newact.sa_mask);
80   newact.sa_flags = 0;
81
82   sigaction (SIGCONT, NULL, &oldact);
83   if (oldact.sa_handler != SIG_IGN)
84     sigaction (SIGCONT, &newact, NULL);
85 #else
86   if (signal (SIGCONT, SIG_IGN) != SIG_IGN)
87     signal (SIGCONT, sighandler);
88 #endif
89
90   my_usleep (requested_delay);
91
92   if (suspended)
93     {
94       /* Calculate time remaining.  */
95       /* FIXME: the code in sleep doesn't use this, so there's no
96          rush to implement it.  */
97     }
98
99   /* FIXME: Restore sig handler?  */
100
101   return suspended;
102 }