From 5aee4fa6661fdf76fe8fa47f842468cfca46a860 Mon Sep 17 00:00:00 2001 From: Freya Murphy Date: Tue, 6 May 2025 12:36:47 -0400 Subject: init improvements --- user/init.c | 84 +++++++++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 62 insertions(+), 22 deletions(-) diff --git a/user/init.c b/user/init.c index 18e70a2..51d8f92 100644 --- a/user/init.c +++ b/user/init.c @@ -3,6 +3,8 @@ #define MAX_ARGS 4 +static long running = 0; + struct proc { pid_t pid; const char *filename; @@ -32,44 +34,82 @@ static int spawn(const char *filename, const char **args) exit(1); } -int main(void) +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); + } +} - // spawn our processes +static struct proc *get_proc(pid_t pid) +{ + struct proc *proc; for (proc = spawn_table; proc->filename != NULL; proc++) { - int pid; - pid = spawn(proc->filename, proc->args); - if (pid < 0) - fprintf(stderr, "init: cannot exec '%s': %d\n", proc->filename, - pid); - proc->pid = pid; + 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; - pid = waitpid(0, &status); - if (pid < 0) + // 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 - for (proc = spawn_table; proc->filename != NULL; proc++) { - if (proc->pid == pid) { - proc->pid = 0; - pid = spawn(proc->filename, proc->args); - if (pid < 0) - fprintf(stderr, "init: cannot exec '%s': %d\n", - proc->filename, pid); - proc->pid = pid; - break; - } - } + proc = get_proc(pid); + if (proc == NULL) + continue; + + spawn_proc_loop(proc); } - // very very bad! + // failed to launch anythingvery very bad! return 1; } -- cgit v1.2.3-freya