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