What is an Init system anyways?
-> An init system is launched by the kernel, like linux.
Init prepares mounts, process reaping, configuration
services and more. On windows its smss, because microsoft
said so, On linux its most popular one its Systemd
For more info go here: Wikipage on Init
#define _POSIX_C_SOURCE 200809L
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mount.h>
#include <sys/reboot.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
if (getpid() != 1) {
fprintf(stderr, "Must be run as PID 1\n");
return 1;
}
// Block signals so they aren't lost and can be handled synchronously
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGUSR1);
sigaddset(&set, SIGUSR2);
sigaddset(&set, SIGCHLD);
sigprocmask(SIG_BLOCK, &set, NULL);
// Mount virtual filesystems
mount("proc", "/proc", "proc", 0, NULL);
mount("sysfs", "/sys", "sysfs", 0, NULL);
setenv("PATH", "/bin:/sbin:/usr/bin:/usr/sbin", 1);
setenv("TERM", "linux", 1);
// Spawn shell
if (fork() == 0) {
// Unblock signals for the child process
sigprocmask(SIG_UNBLOCK, &set, NULL);
char *argv[] = {"/bin/sh", NULL};
execv(argv[0], argv);
perror("execv failed");
exit(1);
}
// Main event loop: handle signals and reap zombies
int sig;
while (1) {
sigwait(&set, &sig);
if (sig == SIGCHLD) {
// Reap all dead children without blocking
while (waitpid(-1, NULL, WNOHANG) > 0);
} else if (sig == SIGUSR1 || sig == SIGUSR2) {
// Gracefully terminate remaining processes
kill(-1, SIGTERM);
sleep(1);
kill(-1, SIGKILL);
// Flush filesystem buffers to disk
sync();
// Execute poweroff or reboot
if (sig == SIGUSR1) {
reboot(RB_POWER_OFF);
} else {
reboot(RB_AUTOBOOT);
}
}
}
return 0;
}