blob: 6c4a9f1f2b7fa3b959c9fcad047d756a3a5048f3 [file] [log] [blame]
"Robert P. J. Day"63fc1a92006-07-02 19:47:05 +00001/* vi: set sw=4 ts=4: */
Mike Frysinger7031f622006-05-08 03:20:50 +00002/* 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
23#include <unistd.h>
24#include <fcntl.h>
25#include <signal.h>
26#include <sys/types.h>
27#include <sys/socket.h>
28#include <sys/select.h>
29
30
31#include "signalpipe.h"
32#include "common.h"
33
34static int signal_pipe[2];
35
36static void signal_handler(int sig)
37{
38 if (send(signal_pipe[1], &sig, sizeof(sig), MSG_DONTWAIT) < 0)
Denis Vlasenko3538b9a2006-09-06 18:36:50 +000039 bb_perror_msg("Could not send signal");
Mike Frysinger7031f622006-05-08 03:20:50 +000040}
41
42
43/* Call this before doing anything else. Sets up the socket pair
44 * and installs the signal handler */
45void udhcp_sp_setup(void)
46{
47 socketpair(AF_UNIX, SOCK_STREAM, 0, signal_pipe);
48 fcntl(signal_pipe[0], F_SETFD, FD_CLOEXEC);
49 fcntl(signal_pipe[1], F_SETFD, FD_CLOEXEC);
50 signal(SIGUSR1, signal_handler);
51 signal(SIGUSR2, signal_handler);
52 signal(SIGTERM, signal_handler);
53}
54
55
56/* Quick little function to setup the rfds. Will return the
57 * max_fd for use with select. Limited in that you can only pass
58 * one extra fd */
59int udhcp_sp_fd_set(fd_set *rfds, int extra_fd)
60{
61 FD_ZERO(rfds);
62 FD_SET(signal_pipe[0], rfds);
63 if (extra_fd >= 0) {
64 fcntl(extra_fd, F_SETFD, FD_CLOEXEC);
65 FD_SET(extra_fd, rfds);
66 }
67 return signal_pipe[0] > extra_fd ? signal_pipe[0] : extra_fd;
68}
69
70
71/* Read a signal from the signal pipe. Returns 0 if there is
72 * no signal, -1 on error (and sets errno appropriately), and
73 * your signal on success */
74int udhcp_sp_read(fd_set *rfds)
75{
76 int sig;
77
78 if (!FD_ISSET(signal_pipe[0], rfds))
79 return 0;
80
81 if (read(signal_pipe[0], &sig, sizeof(sig)) < 0)
82 return -1;
83
84 return sig;
85}