aboutsummaryrefslogtreecommitdiff
path: root/ReapperRun/main.c
blob: ec209d8095b42c3fd9f052d25aa103e6860b02fc (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
/*
 * Starts any programs with PR_SET_CHILD_SUBREAPER on Linux.
 * Author: Yuuta Liang
 */

#define _POSIX_C_SOURCE 200809L
#define _GNU_SOURCE
#include <sys/prctl.h>
#include <err.h>
#include <errno.h>
#include <assert.h>
#include <stddef.h>
#include <unistd.h>
#include <stdlib.h>
#include <limits.h>

#ifndef TEST
int main(int argc, char **argv) {
	int r;
	assert(argc);
	if (argc == 1)
		errx(64, "Usage: %s /path/to/binary [arg1] [arg2] ...",
				argv[0]);
	/* path is not freed on intend. */
	char *path = realpath(argv[1], NULL);
	if (!path)
		err(errno, "realpath(%s)", argv[1]);
	if ((r = prctl(PR_SET_CHILD_SUBREAPER, 1) < 0))
		err(errno, "prctl(PR_SET_CHILD_SUBREAPER)");
	if ((r = execve(path, &argv[1], environ)))
		err(errno, "exec(%s)", path);
}
#else /* ifndef TEST */
#include <stdio.h>
int main(void) {
	printf("Parent PID: %d\n", getpid());
	if (!fork()) {
		printf("Fork PID: %d\n", getpid());
		unsigned int counter = 0;
		goto f;
f:
		counter ++;
		if (!fork()) {
			printf("Child PID: %d\n", getpid());
			pause();
		}
		if (counter < 20) goto f;
		exit(0);
	}
	pause();
}
#endif /* ifndef TEST */