aboutsummaryrefslogtreecommitdiff
path: root/sinit.c
blob: f03996dd32ab2d95a320e7fc603e96f7e40594c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/* See LICENSE file for copyright and license details. */

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "util.h"

static void sigpoweroff(void);
static void sigreap(void);
static void sigreboot(void);
static void spawn(char *const []);

static struct {
	int sig;
	void (*handler)(void);
} sigmap[] = {
	{ SIGUSR1, sigpoweroff },
	{ SIGCHLD, sigreap     },
	{ SIGINT,  sigreboot   },
};

#include "config.h"

static sigset_t set;

int
main(void)
{
	int sig;
	int i;

	if (getpid() != 1)
		return EXIT_FAILURE;
	setsid();

	sigemptyset(&set);
	for (i = 0; i < LEN(sigmap); i++)
		sigaddset(&set, sigmap[i].sig);
	sigprocmask(SIG_BLOCK, &set, NULL);

	spawn(rcinitcmd);

	while (1) {
		sigwait(&set, &sig);
		for (i = 0; i < LEN(sigmap); i++)
			if (sigmap[i].sig == sig)
				sigmap[i].handler();
	}

	/* not reachable */
	return EXIT_SUCCESS;
}

static void
sigpoweroff(void)
{
	spawn(rcpoweroffcmd);
}

static void
sigreap(void)
{
	while (waitpid(-1, NULL, WNOHANG) > 0)
		;
}

static void
sigreboot(void)
{
	spawn(rcrebootcmd);
}

static void
spawn(char *const argv[])
{
	pid_t pid;

	pid = fork();
	if (pid < 0) {
		weprintf("sinit: fork:");
	} else if (pid == 0) {
		sigprocmask(SIG_UNBLOCK, &set, NULL);
		setsid();
		setpgid(0, 0);
		execvp(argv[0], argv);
		weprintf("sinit: execvp %s:", argv[0]);
		_exit(errno == ENOENT ? 127 : 126);
	}
}