Various cleanups I made while going through Erik Hovland's patch submissions,
[oweals/busybox.git] / networking / udhcp / signalpipe.c
1 /* signalpipe.c
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
22 #include <unistd.h>
23 #include <fcntl.h>
24 #include <signal.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/select.h>
28
29
30 #include "signalpipe.h"
31 #include "common.h"
32
33 static int signal_pipe[2];
34
35 static void signal_handler(int sig)
36 {
37         if (send(signal_pipe[1], &sig, sizeof(sig), MSG_DONTWAIT) < 0)
38                 DEBUG(LOG_ERR, "Could not send signal: %m");
39 }
40
41
42 /* Call this before doing anything else. Sets up the socket pair
43  * and installs the signal handler */
44 void udhcp_sp_setup(void)
45 {
46         socketpair(AF_UNIX, SOCK_STREAM, 0, signal_pipe);
47         fcntl(signal_pipe[0], F_SETFD, FD_CLOEXEC);
48         fcntl(signal_pipe[1], F_SETFD, FD_CLOEXEC);
49         signal(SIGUSR1, signal_handler);
50         signal(SIGUSR2, signal_handler);
51         signal(SIGTERM, signal_handler);
52 }
53
54
55 /* Quick little function to setup the rfds. Will return the
56  * max_fd for use with select. Limited in that you can only pass
57  * one extra fd */
58 int udhcp_sp_fd_set(fd_set *rfds, int extra_fd)
59 {
60         FD_ZERO(rfds);
61         FD_SET(signal_pipe[0], rfds);
62         if (extra_fd >= 0) {
63                 fcntl(extra_fd, F_SETFD, FD_CLOEXEC);
64                 FD_SET(extra_fd, rfds);
65         }
66         return signal_pipe[0] > extra_fd ? signal_pipe[0] : extra_fd;
67 }
68
69
70 /* Read a signal from the signal pipe. Returns 0 if there is
71  * no signal, -1 on error (and sets errno appropriately), and
72  * your signal on success */
73 int udhcp_sp_read(fd_set *rfds)
74 {
75         int sig;
76
77         if (!FD_ISSET(signal_pipe[0], rfds))
78                 return 0;
79
80         if (read(signal_pipe[0], &sig, sizeof(sig)) < 0)
81                 return -1;
82
83         return sig;
84 }