summaryrefslogtreecommitdiff
path: root/user/init.c
blob: 51d8f9297d0a80667c3dc26329f247032482b4a1 (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
#include <stdio.h>
#include <unistd.h>

#define MAX_ARGS 4

static long running = 0;

struct proc {
	pid_t pid;
	const char *filename;
	const char *args[MAX_ARGS];
};

static struct proc spawn_table[] = {
	// apple
	{ 0, "bin/apple", { NULL } },
	// end,
	{ 0, NULL, { NULL } },
};

static int spawn(const char *filename, const char **args)
{
	int ret;

	// fork init
	if ((ret = fork()) != 0)
		return ret;

	// call exec
	if ((ret = exec(filename, args)))
		exit(ret);

	// should not happen!
	exit(1);
}

static void spawn_proc(struct proc *proc)
{
	int ret;

	// update running on respawn
	if (proc->pid)
		running--;

	// attempt to fork / exec
	ret = spawn(proc->filename, proc->args);

	// handle result
	if (ret < 0) {
		printf("init: cannot exec '%s': %d\n", proc->filename, ret);
		proc->pid = 0;
	} else {
		running++;
		proc->pid = ret;
	}
}

static void spawn_proc_loop(struct proc *proc)
{
	while (proc->pid == 0)
		spawn_proc(proc);
}

static void spawn_all(void)
{
	struct proc *proc;
	for (proc = spawn_table; proc->filename != NULL; proc++) {
		spawn_proc_loop(proc);
	}
}

static struct proc *get_proc(pid_t pid)
{
	struct proc *proc;
	for (proc = spawn_table; proc->filename != NULL; proc++) {
		if (proc->pid == pid)
			return proc;
	}
	return NULL;
}

int main(void)
{
	// spawn our processes
	spawn_all();

	// clean up dead on restart ours
	while (1) {
		struct proc *proc;
		int pid, status;

		// dont wait if nothing running
		if (running) {
			pid = waitpid(0, &status);
			// ???
			if (pid < 0)
				continue;
		} else {
			spawn_all();
			continue;
		}

		printf("init: pid %d exited with %d\n", pid, status);

		// figure out if this is one of ours
		proc = get_proc(pid);
		if (proc == NULL)
			continue;

		spawn_proc_loop(proc);
	}

	// failed to launch anythingvery very bad!
	return 1;
}