init improvements
This commit is contained in:
parent
fa745d64c6
commit
5aee4fa666
1 changed files with 63 additions and 23 deletions
86
user/init.c
86
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;
|
||||
|
||||
// spawn our processes
|
||||
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;
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue