signal.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
  3. * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU Lesser General Public License version 2.1
  7. * as published by the Free Software Foundation
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. */
  14. #include <sys/reboot.h>
  15. #include <sys/types.h>
  16. #include <unistd.h>
  17. #include "procd.h"
  18. static void do_reboot(void)
  19. {
  20. LOG("reboot\n");
  21. fflush(stderr);
  22. sync();
  23. sleep(2);
  24. reboot(RB_AUTOBOOT);
  25. while (1)
  26. ;
  27. }
  28. static void signal_shutdown(int signal, siginfo_t *siginfo, void *data)
  29. {
  30. int event = 0;
  31. char *msg = NULL;
  32. switch(signal) {
  33. case SIGINT:
  34. case SIGTERM:
  35. event = RB_AUTOBOOT;
  36. msg = "reboot";
  37. break;
  38. case SIGUSR1:
  39. case SIGUSR2:
  40. event = RB_POWER_OFF;
  41. msg = "poweroff";
  42. break;
  43. }
  44. DEBUG(1, "Triggering %s\n", msg);
  45. if (event)
  46. procd_shutdown(event);
  47. }
  48. struct sigaction sa_shutdown = {
  49. .sa_sigaction = signal_shutdown,
  50. .sa_flags = SA_SIGINFO
  51. };
  52. static void signal_crash(int signal, siginfo_t *siginfo, void *data)
  53. {
  54. ERROR("Rebooting as procd has crashed\n");
  55. do_reboot();
  56. }
  57. struct sigaction sa_crash = {
  58. .sa_sigaction = signal_crash,
  59. .sa_flags = SA_SIGINFO
  60. };
  61. static void signal_dummy(int signal, siginfo_t *siginfo, void *data)
  62. {
  63. ERROR("Got unexpected signal %d\n", signal);
  64. }
  65. struct sigaction sa_dummy = {
  66. .sa_sigaction = signal_dummy,
  67. .sa_flags = SA_SIGINFO
  68. };
  69. void procd_signal(void)
  70. {
  71. signal(SIGPIPE, SIG_IGN);
  72. if (getpid() != 1)
  73. return;
  74. sigaction(SIGTERM, &sa_shutdown, NULL);
  75. sigaction(SIGINT, &sa_shutdown, NULL);
  76. sigaction(SIGUSR1, &sa_shutdown, NULL);
  77. sigaction(SIGUSR2, &sa_shutdown, NULL);
  78. sigaction(SIGSEGV, &sa_crash, NULL);
  79. sigaction(SIGBUS, &sa_crash, NULL);
  80. sigaction(SIGHUP, &sa_dummy, NULL);
  81. sigaction(SIGKILL, &sa_dummy, NULL);
  82. sigaction(SIGSTOP, &sa_dummy, NULL);
  83. reboot(RB_DISABLE_CAD);
  84. }