aboutsummaryrefslogtreecommitdiff
path: root/sinit.c
blob: eff65332a9366b519e47280d54764c907e26bc73 (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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/* See LICENSE file for copyright and license details. */

#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/signalfd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "util.h"

typedef union {
        const void *v;
} Arg;

volatile sig_atomic_t signum;

typedef struct {
	int sig;
	void (*func)(void);
} Sigmap;

static void sigreap(void);
static void sigreboot(void);
static void spawn(const Arg *);

static Sigmap dispatchsig[] = {
	{ SIGCHLD, sigreap   },
	{ SIGINT,  sigreboot },
};

static int sigfd = -1;

#include "config.h"

int
main(void)
{
	struct signalfd_siginfo siginfo;
	sigset_t sigset;
	int i;
	int ret;
	ssize_t n;
	fd_set rfds;

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

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

	sigfd = signalfd(-1, &sigset, 0);
	if (sigfd < 0)
		eprintf("sinit: signalfd:");

	spawn(&(Arg){ .v = rcinitcmd });

	while (1) {
		FD_ZERO(&rfds);
		FD_SET(sigfd, &rfds);
		ret = select(sigfd + 1, &rfds, NULL, NULL, NULL);
		if (ret < 0)
			eprintf("sinit: select:");
		if (ret > 0) {
			if (FD_ISSET(sigfd, &rfds)) {
				n = read(sigfd, &siginfo, sizeof(siginfo));
				if (n <= 0)
					continue;
				for (i = 0; i < LEN(dispatchsig); i++)
					if (dispatchsig[i].sig == siginfo.ssi_signo)
						dispatchsig[i].func();
			}
		}
	}

	return EXIT_SUCCESS;
}

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

static void
sigreboot(void)
{
	spawn(&(Arg){ .v = rcrebootcmd });
}

static void
spawn(const Arg *arg)
{
	int status;
	pid_t pid;
	char *const *p = arg->v;

	pid = fork();
	if (pid < 0) {
		weprintf("sinit: fork:");
	} else if (pid == 0) {
		pid = fork();
		if (pid < 0)
			weprintf("sinit: fork:");
		else if (pid > 0)
			exit(0);
		setsid();
		setpgid(0, 0);
		execvp(*p, p);
		weprintf("sinit: execvp %s:", p);
		_exit(errno == ENOENT ? 127 : 126);
	}
	waitpid(pid, &status, 0);
}