sleep.c 821 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. * sleep - suspend current process for a number of seconds
  3. */
  4. /* $Id$ */
  5. #include <signal.h>
  6. #include <setjmp.h>
  7. int _alarm(int n);
  8. void _pause(void);
  9. static jmp_buf setjmpbuf;
  10. static void
  11. alfun(int sig)
  12. {
  13. longjmp(setjmpbuf, 1);
  14. } /* used with sleep() below */
  15. void
  16. sleep(int n)
  17. {
  18. /* sleep(n) pauses for 'n' seconds by scheduling an alarm interrupt. */
  19. unsigned oldalarm = 0;
  20. void (*oldsig)(int) = 0;
  21. if (n <= 0) return;
  22. if (setjmp(setjmpbuf)) {
  23. signal(SIGALRM, oldsig);
  24. _alarm(oldalarm);
  25. return;
  26. }
  27. oldalarm = _alarm(5000); /* Who cares how long, as long
  28. * as it is long enough
  29. */
  30. if (oldalarm > n) oldalarm -= n;
  31. else if (oldalarm) {
  32. n = oldalarm;
  33. oldalarm = 1;
  34. }
  35. oldsig = signal(SIGALRM, alfun);
  36. _alarm(n);
  37. for (;;) {
  38. /* allow for other handlers ... */
  39. _pause();
  40. }
  41. }