xref: /original-bsd/lib/libc/gen/usleep.c (revision e0c0d005)
1 /*
2  * Copyright (c) 1989 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #if defined(LIBC_SCCS) && !defined(lint)
9 static char sccsid[] = "@(#)usleep.c	5.6 (Berkeley) 02/23/91";
10 #endif /* LIBC_SCCS and not lint */
11 
12 #include <sys/time.h>
13 #include <sys/signal.h>
14 #include <unistd.h>
15 
16 #define	TICK	10000		/* system clock resolution in microseconds */
17 #define	USPS	1000000		/* number of microseconds in a second */
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 void
25 usleep(useconds)
26 	unsigned int useconds;
27 {
28 	register struct itimerval *itp;
29 	struct itimerval itv, oitv;
30 	struct sigvec vec, ovec;
31 	long omask;
32 	static void sleephandler();
33 
34 	itp = &itv;
35 	if (!useconds)
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 = useconds / USPS;
42 	itp->it_value.tv_usec = useconds % 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, sleephandler);
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 sleephandler()
71 {
72 	ringring = 1;
73 }
74