xref: /original-bsd/lib/libc/gen/sleep.c (revision ec7df300)
1 /*
2  * Copyright (c) 1980 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 #ifndef lint
8 static char sccsid[] = "@(#)sleep.c	5.1 (Berkeley) 05/30/85";
9 #endif not lint
10 
11 #include <sys/time.h>
12 #include <signal.h>
13 
14 #define	setvec(vec, a) \
15 	vec.sv_handler = a; vec.sv_mask = vec.sv_onstack = 0
16 
17 static int ringring;
18 
19 sleep(n)
20 	unsigned n;
21 {
22 	int sleepx(), omask;
23 	struct itimerval itv, oitv;
24 	register struct itimerval *itp = &itv;
25 	struct sigvec vec, ovec;
26 
27 	if (n == 0)
28 		return;
29 	timerclear(&itp->it_interval);
30 	timerclear(&itp->it_value);
31 	if (setitimer(ITIMER_REAL, itp, &oitv) < 0)
32 		return;
33 	itp->it_value.tv_sec = n;
34 	if (timerisset(&oitv.it_value)) {
35 		if (timercmp(&oitv.it_value, &itp->it_value, >))
36 			oitv.it_value.tv_sec -= itp->it_value.tv_sec;
37 		else {
38 			itp->it_value = oitv.it_value;
39 			/*
40 			 * This is a hack, but we must have time to
41 			 * return from the setitimer after the alarm
42 			 * or else it'll be restarted.  And, anyway,
43 			 * sleep never did anything more than this before.
44 			 */
45 			oitv.it_value.tv_sec = 1;
46 			oitv.it_value.tv_usec = 0;
47 		}
48 	}
49 	setvec(vec, sleepx);
50 	(void) sigvec(SIGALRM, &vec, &ovec);
51 	omask = sigblock(sigmask(SIGALRM));
52 	ringring = 0;
53 	(void) setitimer(ITIMER_REAL, itp, (struct itimerval *)0);
54 	while (!ringring)
55 		sigpause(omask &~ sigmask(SIGALRM));
56 	(void) sigvec(SIGALRM, &ovec, (struct sigvec *)0);
57 	(void) sigsetmask(omask);
58 	(void) setitimer(ITIMER_REAL, &oitv, (struct itimerval *)0);
59 }
60 
61 static
62 sleepx()
63 {
64 
65 	ringring = 1;
66 }
67