blob: 074c8a6037ea2d752cd3df70bfbd2882ac6fcb70 [file] [log] [blame]
Russ Dill4e864a32003-12-18 22:25:38 +00001/* signalpipe.c
2 *
Eric Andersenaff114c2004-04-14 17:51:38 +00003 * Signal pipe infrastructure. A reliable way of delivering signals.
Russ Dill4e864a32003-12-18 22:25:38 +00004 *
Eric Andersenaff114c2004-04-14 17:51:38 +00005 * Russ Dill <Russ.Dill@asu.edu> December 2003
Russ Dill4e864a32003-12-18 22:25:38 +00006 *
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
22#include <unistd.h>
23#include <signal.h>
24#include <sys/types.h>
25#include <sys/socket.h>
26#include <sys/select.h>
27
28
29#include "signalpipe.h"
30#include "common.h"
31
32static int signal_pipe[2];
33
34static void signal_handler(int sig)
35{
36 if (send(signal_pipe[1], &sig, sizeof(sig), MSG_DONTWAIT) < 0)
37 DEBUG(LOG_ERR, "Could not send signal: %m");
38}
39
40
41/* Call this before doing anything else. Sets up the socket pair
42 * and installs the signal handler */
43void udhcp_sp_setup(void)
44{
45 socketpair(AF_UNIX, SOCK_STREAM, 0, signal_pipe);
46 signal(SIGUSR1, signal_handler);
47 signal(SIGUSR2, signal_handler);
48 signal(SIGTERM, signal_handler);
49}
50
51
52/* Quick little function to setup the rfds. Will return the
53 * max_fd for use with select. Limited in that you can only pass
54 * one extra fd */
55int udhcp_sp_fd_set(fd_set *rfds, int extra_fd)
56{
57 FD_ZERO(rfds);
58 FD_SET(signal_pipe[0], rfds);
59 if (extra_fd >= 0) FD_SET(extra_fd, rfds);
60 return signal_pipe[0] > extra_fd ? signal_pipe[0] : extra_fd;
61}
62
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 */
67int udhcp_sp_read(fd_set *rfds)
68{
69 int sig;
70
71 if (!FD_ISSET(signal_pipe[0], rfds))
72 return 0;
73
74 if (read(signal_pipe[0], &sig, sizeof(sig)) < 0)
75 return -1;
76
77 return sig;
78}