summaryrefslogtreecommitdiff
path: root/4init/4init.c
blob: 14cfbba35603d054976c0659dde3f6c9e660a3fb (plain) (blame)
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
#define _POSIX_C_SOURCE 200809L

#include <signal.h>
#include <stdio.h>
#include <sys/signalfd.h>
#include <sys/wait.h>
#include <unistd.h>

#include "config.h"

static void reap(void) {
	int status;
	while (waitpid(-1, &status, WNOHANG) > 0) {
	}
}

int main(void) {
	int sigfd = -1;
	pid_t pid = -1;
	sigset_t set;

	if (getpid() != 1) {
		fprintf(stderr, "4init - you need to run this as PID 1...\n");
		return 1;
	}

	sigfillset(&set);
	sigdelset(&set, SIGILL);
	sigdelset(&set, SIGTRAP);
	sigdelset(&set, SIGBUS);
	sigdelset(&set, SIGFPE);
	sigdelset(&set, SIGSEGV);

	if (sigprocmask(SIG_SETMASK, &set, NULL) < 0) {
		perror("sigprocmask");
		return 1;
	}

	sigfd = signalfd(-1, &set, SFD_CLOEXEC);
	if (sigfd < 0) {
		perror("signalfd");
		return 1;
	}

	pid = fork();
	if (pid < 0) {
		perror("fork");
		return 1;
	}

	if (pid == 0) {
		sigset_t empty_set;

		sigemptyset(&empty_set);
		sigprocmask(SIG_SETMASK, &empty_set, NULL);

		if (setsid() == -1) {
			perror("setsid");
		}

		close(sigfd);

		execve(rc_path, rc_argv, rc_envp);
		perror("execve");
		_exit(1);
	} else {
		struct signalfd_siginfo fdsi;

		reap();

		for (;;) {
			if (read(sigfd, &fdsi, sizeof(fdsi)) == sizeof(fdsi)) {
				switch (fdsi.ssi_signo) {
				case SIGCHLD:
					reap();
					break;
				}
			}
		}
	}
}