xref: /titanic_50/usr/src/lib/libbc/libc/gen/common/usleep.c (revision e127a3e717f822eb855235fa3bd08235b2cf533d)
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 #pragma ident	"%Z%%M%	%I%	%E% SMI"
13 
14 #include <unistd.h>
15 #include <sys/time.h>
16 #include <signal.h>
17 
18 #define	USPS	1000000		/* number of microseconds in a second */
19 #define	TICK	(USPS / _sysconf(_SC_CLK_TCK))
20 
21 #define	setvec(vec, a) \
22 	vec.sv_handler = a; vec.sv_mask = vec.sv_onstack = 0
23 
24 static int ringring;
25 
26 void
27 usleep(unsigned n)
28 {
29 	static void sleepx();
30 	int omask;
31 	struct itimerval itv, oitv;
32 	struct itimerval *itp = &itv;
33 	struct sigvec vec, ovec;
34 
35 	if (n == 0)
36 		return;
37 	timerclear(&itp->it_interval);
38 	timerclear(&itp->it_value);
39 	if (setitimer(ITIMER_REAL, itp, &oitv) < 0)
40 		return;
41 	itp->it_value.tv_sec = n / USPS;
42 	itp->it_value.tv_usec = n % USPS;
43 	if (timerisset(&oitv.it_value)) {
44 		if (timercmp(&oitv.it_value, &itp->it_value, >)) {
45 			oitv.it_value.tv_sec -= itp->it_value.tv_sec;
46 			oitv.it_value.tv_usec -= itp->it_value.tv_usec;
47 			if (oitv.it_value.tv_usec < 0) {
48 				oitv.it_value.tv_usec += USPS;
49 				oitv.it_value.tv_sec--;
50 			}
51 		} else {
52 			itp->it_value = oitv.it_value;
53 			oitv.it_value.tv_sec = 0;
54 			oitv.it_value.tv_usec = 2 * TICK;
55 		}
56 	}
57 	setvec(vec, sleepx);
58 	(void) sigvec(SIGALRM, &vec, &ovec);
59 	omask = sigblock(sigmask(SIGALRM));
60 	ringring = 0;
61 	(void) setitimer(ITIMER_REAL, itp, (struct itimerval *)0);
62 	while (!ringring)
63 		sigpause(omask &~ sigmask(SIGALRM));
64 	(void) sigvec(SIGALRM, &ovec, (struct sigvec *)0);
65 	(void) sigsetmask(omask);
66 	(void) setitimer(ITIMER_REAL, &oitv, (struct itimerval *)0);
67 }
68 
69 static void
70 sleepx(void)
71 {
72 
73 	ringring = 1;
74 }
75