3
0

signalpipe.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Signal pipe infrastructure. A reliable way of delivering signals.
  4. *
  5. * Russ Dill <Russ.Dill@asu.edu> December 2003
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  20. */
  21. #include "common.h"
  22. /* Global variable: we access it from signal handler */
  23. static struct fd_pair signal_pipe;
  24. static void signal_handler(int sig)
  25. {
  26. int sv = errno;
  27. unsigned char ch = sig; /* use char, avoid dealing with partial writes */
  28. if (write(signal_pipe.wr, &ch, 1) != 1)
  29. bb_perror_msg("can't send signal");
  30. errno = sv;
  31. }
  32. /* Call this before doing anything else. Sets up the socket pair
  33. * and installs the signal handler */
  34. void FAST_FUNC udhcp_sp_setup(void)
  35. {
  36. /* was socketpair, but it needs AF_UNIX in kernel */
  37. xpiped_pair(signal_pipe);
  38. close_on_exec_on(signal_pipe.rd);
  39. close_on_exec_on(signal_pipe.wr);
  40. ndelay_on(signal_pipe.rd);
  41. ndelay_on(signal_pipe.wr);
  42. bb_signals(0
  43. + (1 << SIGUSR1)
  44. + (1 << SIGUSR2)
  45. + (1 << SIGTERM)
  46. , signal_handler);
  47. }
  48. /* Quick little function to setup the pfds.
  49. * Limited in that you can only pass one extra fd.
  50. */
  51. void FAST_FUNC udhcp_sp_fd_set(struct pollfd pfds[2], int extra_fd)
  52. {
  53. pfds[0].fd = signal_pipe.rd;
  54. pfds[0].events = POLLIN;
  55. pfds[1].fd = -1;
  56. if (extra_fd >= 0) {
  57. close_on_exec_on(extra_fd);
  58. pfds[1].fd = extra_fd;
  59. pfds[1].events = POLLIN;
  60. }
  61. /* this simplifies "is extra_fd ready?" tests elsewhere: */
  62. pfds[1].revents = 0;
  63. }
  64. /* Read a signal from the signal pipe. Returns 0 if there is
  65. * no signal, -1 on error (and sets errno appropriately), and
  66. * your signal on success */
  67. int FAST_FUNC udhcp_sp_read(void)
  68. {
  69. unsigned char sig;
  70. /* Can't block here, fd is in nonblocking mode */
  71. if (safe_read(signal_pipe.rd, &sig, 1) != 1)
  72. return 0;
  73. return sig;
  74. }