UPS: apcupsd clean sources
[tomato.git] / release / src / router / apcupsd / src / lib / sleep.c
blob41ee7ce1b1e1166610088204cde9e2edfcab1377
1 /*
2 * sleep.c
4 * Implementations of sleep-related functions for platforms that
5 * do not already have them.
6 */
8 /*
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of version 2 of the GNU General
11 * Public License as published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
18 * You should have received a copy of the GNU General Public
19 * License along with this program; if not, write to the Free
20 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
21 * MA 02111-1307, USA.
24 #include "apc.h"
26 #ifndef HAVE_NANOSLEEP
28 * This is a close approximation of nanosleep() for platforms that
29 * do not have it.
31 int nanosleep(const struct timespec *req, struct timespec *rem)
33 static pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
34 static pthread_cond_t timer = PTHREAD_COND_INITIALIZER;
35 struct timespec timeout;
36 int stat;
38 struct timeval tv;
40 /* Copy relative exit time */
41 timeout = *req;
43 /* Compute absolute exit time */
44 gettimeofday(&tv, NULL);
45 timeout.tv_nsec += tv.tv_usec * 1000;
46 timeout.tv_sec += tv.tv_sec;
47 while (timeout.tv_nsec >= 1000000000) {
48 timeout.tv_nsec -= 1000000000;
49 timeout.tv_sec++;
52 Dmsg1(200, "pthread_cond_timedwait sec=%d\n", timeout.tv_sec);
54 /* Mutex is unlocked during the timedwait */
55 P(timer_mutex);
57 stat = pthread_cond_timedwait(&timer, &timer_mutex, &timeout);
58 Dmsg1(200, "pthread_cond_timedwait stat=%d\n", stat);
60 V(timer_mutex);
62 /* Assume no time leftover */
63 if (rem) {
64 rem->tv_nsec = 0;
65 rem->tv_sec = 0;
68 return 0;
70 #endif /* HAVE_NANOSLEEP */