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.2 (Berkeley) 03/09/86"; 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(), omask; 26 struct itimerval itv, oitv; 27 register struct itimerval *itp = &itv; 28 struct sigvec vec, ovec; 29 30 if (n == 0) 31 return; 32 timerclear(&itp->it_interval); 33 timerclear(&itp->it_value); 34 if (setitimer(ITIMER_REAL, itp, &oitv) < 0) 35 return; 36 itp->it_value.tv_sec = n / USPS; 37 itp->it_value.tv_usec = n % USPS; 38 if (timerisset(&oitv.it_value)) { 39 if (timercmp(&oitv.it_value, &itp->it_value, >)) { 40 oitv.it_value.tv_sec -= itp->it_value.tv_sec; 41 oitv.it_value.tv_usec -= itp->it_value.tv_usec; 42 if (oitv.it_value.tv_usec < 0) { 43 oitv.it_value.tv_usec += USPS; 44 oitv.it_value.tv_sec--; 45 } 46 } else { 47 itp->it_value = oitv.it_value; 48 oitv.it_value.tv_sec = 0; 49 oitv.it_value.tv_usec = 2 * TICK; 50 } 51 } 52 setvec(vec, sleepx); 53 (void) sigvec(SIGALRM, &vec, &ovec); 54 omask = sigblock(sigmask(SIGALRM)); 55 ringring = 0; 56 (void) setitimer(ITIMER_REAL, itp, (struct itimerval *)0); 57 while (!ringring) 58 sigpause(omask &~ sigmask(SIGALRM)); 59 (void) sigvec(SIGALRM, &ovec, (struct sigvec *)0); 60 (void) sigsetmask(omask); 61 (void) setitimer(ITIMER_REAL, &oitv, (struct itimerval *)0); 62 } 63 64 static 65 sleepx() 66 { 67 68 ringring = 1; 69 } 70