signalpipe.c 2.2 KB

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