add state handler
[project/procd.git] / signal.c
1 /*
2  * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3  * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License version 2.1
7  * as published by the Free Software Foundation
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include <sys/reboot.h>
16 #include <sys/types.h>
17
18 #include <unistd.h>
19
20 #include "procd.h"
21
22 static void signal_shutdown(int signal, siginfo_t *siginfo, void *data)
23 {
24         int event = 0;
25         char *msg = NULL;
26
27         switch(signal) {
28         case SIGTERM:
29                 event = RB_AUTOBOOT;
30                 msg = "reboot";
31                 break;
32         case SIGUSR1:
33         case SIGUSR2:
34                 event = RB_POWER_OFF;
35                 msg = "poweroff";
36                 break;
37         }
38
39         DEBUG(1, "Triggering %s\n", msg);
40         if (event)
41                 procd_shutdown(event);
42 }
43
44 struct sigaction sa_shutdown = {
45         .sa_sigaction = signal_shutdown,
46         .sa_flags = SA_SIGINFO
47 };
48
49 static void signal_crash(int signal, siginfo_t *siginfo, void *data)
50 {
51         ERROR("Rebooting as procd has crashed\n");
52         fflush(stderr);
53         sync();
54         sleep(1);
55         reboot(RB_AUTOBOOT);
56         while (1)
57                 ;
58 }
59
60 struct sigaction sa_crash = {
61         .sa_sigaction = signal_crash,
62         .sa_flags = SA_SIGINFO
63 };
64
65 static void signal_dummy(int signal, siginfo_t *siginfo, void *data)
66 {
67         ERROR("Got unexpected signal %d\n", signal);
68 }
69
70 struct sigaction sa_dummy = {
71         .sa_sigaction = signal_dummy,
72         .sa_flags = SA_SIGINFO
73 };
74
75 void procd_signal(void)
76 {
77         sigaction(SIGPIPE, &sa_dummy, NULL);
78         if (getpid() != 1)
79                 return;
80         sigaction(SIGTERM, &sa_shutdown, NULL);
81         sigaction(SIGUSR1, &sa_shutdown, NULL);
82         sigaction(SIGUSR2, &sa_shutdown, NULL);
83         sigaction(SIGSEGV, &sa_crash, NULL);
84         sigaction(SIGBUS, &sa_crash, NULL);
85         sigaction(SIGHUP, &sa_dummy, NULL);
86         sigaction(SIGKILL, &sa_dummy, NULL);
87         sigaction(SIGSTOP, &sa_dummy, NULL);
88 }