xref: /titanic_50/usr/src/lib/libbc/libc/gen/common/usleep.c (revision 2bc987325e3ded1865bff043128661815c4690b9)
1 /*
2  * Copyright 1996 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 
6 /*
7  * Copyright (c) 1985 Regents of the University of California.
8  * All rights reserved.  The Berkeley software License Agreement
9  * specifies the terms and conditions for redistribution.
10  */
11 
12 #include <unistd.h>
13 #include <sys/time.h>
14 #include <signal.h>
15 
16 #define	USPS	1000000		/* number of microseconds in a second */
17 #define	TICK	(USPS / _sysconf(_SC_CLK_TCK))
18 
19 #define	setvec(vec, a) \
20 	vec.sv_handler = a; vec.sv_mask = vec.sv_onstack = 0
21 
22 static int ringring;
23 
24 static void
25 sleepx(void)
26 {
27 
28 	ringring = 1;
29 }
30 
31 void
32 usleep(unsigned n)
33 {
34 	int omask;
35 	struct itimerval itv, oitv;
36 	struct itimerval *itp = &itv;
37 	struct sigvec vec, ovec;
38 
39 	if (n == 0)
40 		return;
41 	timerclear(&itp->it_interval);
42 	timerclear(&itp->it_value);
43 	if (setitimer(ITIMER_REAL, itp, &oitv) < 0)
44 		return;
45 	itp->it_value.tv_sec = n / USPS;
46 	itp->it_value.tv_usec = n % USPS;
47 	if (timerisset(&oitv.it_value)) {
48 		if (timercmp(&oitv.it_value, &itp->it_value, >)) {
49 			oitv.it_value.tv_sec -= itp->it_value.tv_sec;
50 			oitv.it_value.tv_usec -= itp->it_value.tv_usec;
51 			if (oitv.it_value.tv_usec < 0) {
52 				oitv.it_value.tv_usec += USPS;
53 				oitv.it_value.tv_sec--;
54 			}
55 		} else {
56 			itp->it_value = oitv.it_value;
57 			oitv.it_value.tv_sec = 0;
58 			oitv.it_value.tv_usec = 2 * TICK;
59 		}
60 	}
61 	setvec(vec, sleepx);
62 	(void) sigvec(SIGALRM, &vec, &ovec);
63 	omask = sigblock(sigmask(SIGALRM));
64 	ringring = 0;
65 	(void) setitimer(ITIMER_REAL, itp, (struct itimerval *)0);
66 	while (!ringring)
67 		sigpause(omask &~ sigmask(SIGALRM));
68 	(void) sigvec(SIGALRM, &ovec, (struct sigvec *)0);
69 	(void) sigsetmask(omask);
70 	(void) setitimer(ITIMER_REAL, &oitv, (struct itimerval *)0);
71 }
72