sigchain.c 976 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include "sigchain.h"
  2. #include "cache.h"
  3. #define SIGCHAIN_MAX_SIGNALS 32
  4. struct sigchain_signal {
  5. sigchain_fun *old;
  6. int n;
  7. int alloc;
  8. };
  9. static struct sigchain_signal signals[SIGCHAIN_MAX_SIGNALS];
  10. static void check_signum(int sig)
  11. {
  12. if (sig < 1 || sig >= SIGCHAIN_MAX_SIGNALS)
  13. die("BUG: signal out of range: %d", sig);
  14. }
  15. static int sigchain_push(int sig, sigchain_fun f)
  16. {
  17. struct sigchain_signal *s = signals + sig;
  18. check_signum(sig);
  19. ALLOC_GROW(s->old, s->n + 1, s->alloc);
  20. s->old[s->n] = signal(sig, f);
  21. if (s->old[s->n] == SIG_ERR)
  22. return -1;
  23. s->n++;
  24. return 0;
  25. }
  26. int sigchain_pop(int sig)
  27. {
  28. struct sigchain_signal *s = signals + sig;
  29. check_signum(sig);
  30. if (s->n < 1)
  31. return 0;
  32. if (signal(sig, s->old[s->n - 1]) == SIG_ERR)
  33. return -1;
  34. s->n--;
  35. return 0;
  36. }
  37. void sigchain_push_common(sigchain_fun f)
  38. {
  39. sigchain_push(SIGINT, f);
  40. sigchain_push(SIGHUP, f);
  41. sigchain_push(SIGTERM, f);
  42. sigchain_push(SIGQUIT, f);
  43. sigchain_push(SIGPIPE, f);
  44. }