1 /* vi: set sw=4 ts=4: */
3 * Mini init implementation for busybox
5 * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
6 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7 * Adjusted by so many folks, it's impossible to keep track.
9 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
15 #include <sys/reboot.h>
16 #include <sys/resource.h>
20 /* Was a CONFIG_xxx option. A lot of people were building
21 * not fully functional init by switching it on! */
24 #define COMMAND_SIZE 256
25 #define CONSOLE_NAME_SIZE 32
27 /* Default sysinit script. */
29 #define INIT_SCRIPT "/etc/init.d/rcS"
32 /* Each type of actions can appear many times. They will be
33 * handled in order. RESTART is an exception, only 1st is used.
35 /* Start these actions first and wait for completion */
37 /* Start these after SYSINIT and wait for completion */
39 /* Start these after WAIT and *dont* wait for completion */
42 * NB: while SYSINIT/WAIT/ONCE are being processed,
43 * SIGHUP ("reread /etc/inittab") will be processed only after
44 * each group of actions. If new inittab adds, say, a SYSINIT action,
45 * it will not be run, since init is already "past SYSINIT stage".
47 /* Start these after ONCE are started, restart on exit */
49 /* Like RESPAWN, but wait for <Enter> to be pressed on tty */
52 * Start these on SIGINT, and wait for completion.
53 * Then go back to respawning RESPAWN and ASKFIRST actions.
54 * NB: kernel sends SIGINT to us if Ctrl-Alt-Del was pressed.
56 #define CTRLALTDEL 0x20
58 * Start these before killing all processes in preparation for
59 * running RESTART actions or doing low-level halt/reboot/poweroff
60 * (initiated by SIGUSR1/SIGTERM/SIGUSR2).
61 * Wait for completion before proceeding.
65 * exec() on SIGQUIT. SHUTDOWN actions are started and waited for,
66 * then all processes are killed, then init exec's 1st RESTART action,
67 * replacing itself by it. If no RESTART action specified,
68 * SIGQUIT has no effect.
73 /* A linked list of init_actions, to be read from inittab */
75 struct init_action *next;
78 char terminal[CONSOLE_NAME_SIZE];
79 char command[COMMAND_SIZE];
82 static struct init_action *init_action_list = NULL;
84 static const char *log_console = VC_5;
89 #ifndef RB_HALT_SYSTEM
90 RB_HALT_SYSTEM = 0xcdef0123, /* FIXME: this overflows enum */
91 RB_ENABLE_CAD = 0x89abcdef,
93 RB_POWER_OFF = 0x4321fedc,
94 RB_AUTOBOOT = 0x01234567,
98 /* Print a message to the specified device.
99 * "where" may be bitwise-or'd from L_LOG | L_CONSOLE
100 * NB: careful, we can be called after vfork!
102 #define dbg_message(...) do { if (DEBUG_INIT) message(__VA_ARGS__); } while (0)
103 static void message(int where, const char *fmt, ...)
104 __attribute__ ((format(printf, 2, 3)));
105 static void message(int where, const char *fmt, ...)
112 va_start(arguments, fmt);
113 l = 1 + vsnprintf(msg + 1, sizeof(msg) - 2, fmt, arguments);
114 if (l > sizeof(msg) - 1)
118 #if ENABLE_FEATURE_INIT_SYSLOG
121 /* Log the message to syslogd */
122 openlog("init", 0, LOG_DAEMON);
123 /* don't print "\r" */
124 syslog(LOG_INFO, "%s", msg + 1);
131 static int log_fd = -1;
135 /* Take full control of the log tty, and never close it.
136 * It's mine, all mine! Muhahahaha! */
139 log_fd = STDERR_FILENO;
141 log_fd = device_open(log_console, O_WRONLY | O_NONBLOCK | O_NOCTTY);
143 bb_error_msg("can't log to %s", log_console);
146 close_on_exec_on(log_fd);
151 full_write(log_fd, msg, l);
152 if (log_fd == STDERR_FILENO)
153 return; /* don't print dup messages */
158 if (where & L_CONSOLE) {
159 /* Send console messages to console so people will see them. */
160 full_write(STDERR_FILENO, msg, l);
164 static void console_init(void)
169 s = getenv("CONSOLE");
171 s = getenv("console");
173 int fd = open(s, O_RDWR | O_NONBLOCK | O_NOCTTY);
175 dup2(fd, STDIN_FILENO);
176 dup2(fd, STDOUT_FILENO);
177 xmove_fd(fd, STDERR_FILENO);
179 dbg_message(L_LOG, "console='%s'", s);
181 /* Make sure fd 0,1,2 are not closed
182 * (so that they won't be used by future opens) */
184 // Users report problems
185 // /* Make sure init can't be blocked by writing to stderr */
186 // fcntl(STDERR_FILENO, F_SETFL, fcntl(STDERR_FILENO, F_GETFL) | O_NONBLOCK);
190 if (ioctl(STDIN_FILENO, VT_OPENQRY, &vtno) != 0) {
191 /* Not a linux terminal, probably serial console.
192 * Force the TERM setting to vt102
193 * if TERM is set to linux (the default) */
194 if (!s || strcmp(s, "linux") == 0)
195 putenv((char*)"TERM=vt102");
196 if (!ENABLE_FEATURE_INIT_SYSLOG)
199 putenv((char*)"TERM=linux");
202 /* Set terminal settings to reasonable defaults.
203 * NB: careful, we can be called after vfork! */
204 static void set_sane_term(void)
208 tcgetattr(STDIN_FILENO, &tty);
210 /* set control chars */
211 tty.c_cc[VINTR] = 3; /* C-c */
212 tty.c_cc[VQUIT] = 28; /* C-\ */
213 tty.c_cc[VERASE] = 127; /* C-? */
214 tty.c_cc[VKILL] = 21; /* C-u */
215 tty.c_cc[VEOF] = 4; /* C-d */
216 tty.c_cc[VSTART] = 17; /* C-q */
217 tty.c_cc[VSTOP] = 19; /* C-s */
218 tty.c_cc[VSUSP] = 26; /* C-z */
220 /* use line discipline 0 */
223 /* Make it be sane */
224 tty.c_cflag &= CBAUD | CBAUDEX | CSIZE | CSTOPB | PARENB | PARODD;
225 tty.c_cflag |= CREAD | HUPCL | CLOCAL;
228 tty.c_iflag = ICRNL | IXON | IXOFF;
231 tty.c_oflag = OPOST | ONLCR;
235 ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN;
237 tcsetattr_stdin_TCSANOW(&tty);
240 /* Open the new terminal device.
241 * NB: careful, we can be called after vfork! */
242 static int open_stdio_to_tty(const char* tty_name)
244 /* empty tty_name means "use init's tty", else... */
249 /* fd can be only < 0 or 0: */
250 fd = device_open(tty_name, O_RDWR);
252 message(L_LOG | L_CONSOLE, "can't open %s: %s",
253 tty_name, strerror(errno));
254 return 0; /* failure */
256 dup2(STDIN_FILENO, STDOUT_FILENO);
257 dup2(STDIN_FILENO, STDERR_FILENO);
260 return 1; /* success */
263 /* Wrapper around exec:
264 * Takes string (max COMMAND_SIZE chars).
265 * If chars like '>' detected, execs '[-]/bin/sh -c "exec ......."'.
266 * Otherwise splits words on whitespace, deals with leading dash,
267 * and uses plain exec().
268 * NB: careful, we can be called after vfork!
270 static void init_exec(const char *command)
272 char *cmd[COMMAND_SIZE / 2];
273 char buf[COMMAND_SIZE + 6]; /* COMMAND_SIZE+strlen("exec ")+1 */
274 int dash = (command[0] == '-' /* maybe? && command[1] == '/' */);
276 /* See if any special /bin/sh requiring characters are present */
277 if (strpbrk(command, "~`!$^&*()=|\\{}[];\"'<>?") != NULL) {
278 strcpy(buf, "exec ");
279 strcpy(buf + 5, command + dash); /* excluding "-" */
280 /* NB: LIBBB_DEFAULT_LOGIN_SHELL define has leading dash */
281 cmd[0] = (char*)(LIBBB_DEFAULT_LOGIN_SHELL + !dash);
282 cmd[1] = (char*)"-c";
286 /* Convert command (char*) into cmd (char**, one word per string) */
289 next = strcpy(buf, command); /* including "-" */
290 while ((word = strsep(&next, " \t")) != NULL) {
291 if (*word != '\0') { /* not two spaces/tabs together? */
298 /* If we saw leading "-", it is interactive shell.
299 * Try harder to give it a controlling tty.
300 * And skip "-" in actual exec call. */
302 /* _Attempt_ to make stdin a controlling tty. */
303 if (ENABLE_FEATURE_INIT_SCTTY)
304 ioctl(STDIN_FILENO, TIOCSCTTY, 0 /*only try, don't steal*/);
306 BB_EXECVP(cmd[0] + dash, cmd);
307 message(L_LOG | L_CONSOLE, "can't run '%s': %s", cmd[0], strerror(errno));
308 /* returns if execvp fails */
311 /* Used only by run_actions */
312 static pid_t run(const struct init_action *a)
316 /* Careful: don't be affected by a signal in vforked child */
317 sigprocmask_allsigs(SIG_BLOCK);
318 if (BB_MMU && (a->action_type & ASKFIRST))
323 message(L_LOG | L_CONSOLE, "can't fork");
325 sigprocmask_allsigs(SIG_UNBLOCK);
326 return pid; /* Parent or error */
331 /* Reset signal handlers that were set by the parent process */
341 sigprocmask_allsigs(SIG_UNBLOCK);
343 /* Create a new session and make ourself the process group leader */
346 /* Open the new terminal device */
347 if (!open_stdio_to_tty(a->terminal))
350 /* NB: on NOMMU we can't wait for input in child, so
351 * "askfirst" will work the same as "respawn". */
352 if (BB_MMU && (a->action_type & ASKFIRST)) {
353 static const char press_enter[] ALIGN1 =
354 #ifdef CUSTOMIZED_BANNER
355 #include CUSTOMIZED_BANNER
357 "\nPlease press Enter to activate this console. ";
360 * Save memory by not exec-ing anything large (like a shell)
361 * before the user wants it. This is critical if swap is not
362 * enabled and the system has low memory. Generally this will
363 * be run on the second virtual console, and the first will
364 * be allowed to start a shell or whatever an init script
367 dbg_message(L_LOG, "waiting for enter to start '%s'"
368 "(pid %d, tty '%s')\n",
369 a->command, getpid(), a->terminal);
370 full_write(STDOUT_FILENO, press_enter, sizeof(press_enter) - 1);
371 while (safe_read(STDIN_FILENO, &c, 1) == 1 && c != '\n')
376 * When a file named /.init_enable_core exists, setrlimit is called
377 * before processes are spawned to set core file size as unlimited.
378 * This is for debugging only. Don't use this is production, unless
379 * you want core dumps lying about....
381 if (ENABLE_FEATURE_INIT_COREDUMPS) {
382 if (access("/.init_enable_core", F_OK) == 0) {
384 limit.rlim_cur = RLIM_INFINITY;
385 limit.rlim_max = RLIM_INFINITY;
386 setrlimit(RLIMIT_CORE, &limit);
390 /* Log the process name and args */
391 message(L_LOG, "starting pid %d, tty '%s': '%s'",
392 getpid(), a->terminal, a->command);
394 /* Now run it. The new program will take over this PID,
395 * so nothing further in init.c should be run. */
396 init_exec(a->command);
397 /* We're still here? Some error happened. */
401 static struct init_action *mark_terminated(pid_t pid)
403 struct init_action *a;
406 for (a = init_action_list; a; a = a->next) {
416 static void waitfor(pid_t pid)
418 /* waitfor(run(x)): protect against failed fork inside run() */
422 /* Wait for any child (prevent zombies from exiting orphaned processes)
423 * but exit the loop only when specified one has exited. */
425 pid_t wpid = wait(NULL);
426 mark_terminated(wpid);
427 /* Unsafe. SIGTSTP handler might have wait'ed it already */
428 /*if (wpid == pid) break;*/
435 /* Run all commands of a particular type */
436 static void run_actions(int action_type)
438 struct init_action *a;
440 for (a = init_action_list; a; a = a->next) {
441 if (!(a->action_type & action_type))
444 if (a->action_type & (SYSINIT | WAIT | ONCE | CTRLALTDEL | SHUTDOWN)) {
446 if (a->action_type & (SYSINIT | WAIT | CTRLALTDEL | SHUTDOWN))
449 if (a->action_type & (RESPAWN | ASKFIRST)) {
450 /* Only run stuff with pid == 0. If pid != 0,
451 * it is already running
459 static void new_init_action(uint8_t action_type, const char *command, const char *cons)
461 struct init_action *a, **nextp;
465 * ::shutdown:umount -a -r
466 * ::shutdown:swapoff -a
468 * ::shutdown:swapoff -a
469 * ::shutdown:umount -a -r
470 * On reload, we must ensure entries end up in correct order.
471 * To achieve that, if we find a matching entry, we move it
474 nextp = &init_action_list;
475 while ((a = *nextp) != NULL) {
476 /* Don't enter action if it's already in the list,
477 * This prevents losing running RESPAWNs.
479 if ((strcmp(a->command, command) == 0)
480 && (strcmp(a->terminal, cons) == 0)
482 /* Remove from list */
484 /* Find the end of the list */
485 while (*nextp != NULL)
486 nextp = &(*nextp)->next;
494 a = xzalloc(sizeof(*a));
495 /* Append to the end of the list */
497 a->action_type = action_type;
498 safe_strncpy(a->command, command, sizeof(a->command));
499 safe_strncpy(a->terminal, cons, sizeof(a->terminal));
500 dbg_message(L_LOG | L_CONSOLE, "command='%s' action=%d tty='%s'\n",
501 a->command, a->action_type, a->terminal);
504 /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
505 * then parse_inittab() simply adds in some default
506 * actions(i.e., runs INIT_SCRIPT and then starts a pair
507 * of "askfirst" shells). If CONFIG_FEATURE_USE_INITTAB
508 * _is_ defined, but /etc/inittab is missing, this
509 * results in the same set of default behaviors.
511 static void parse_inittab(void)
513 #if ENABLE_FEATURE_USE_INITTAB
515 parser_t *parser = config_open2("/etc/inittab", fopen_for_read);
520 /* No inittab file - set up some default behavior */
521 /* Reboot on Ctrl-Alt-Del */
522 new_init_action(CTRLALTDEL, "reboot", "");
523 /* Umount all filesystems on halt/reboot */
524 new_init_action(SHUTDOWN, "umount -a -r", "");
525 /* Swapoff on halt/reboot */
526 if (ENABLE_SWAPONOFF)
527 new_init_action(SHUTDOWN, "swapoff -a", "");
528 /* Prepare to restart init when a QUIT is received */
529 new_init_action(RESTART, "init", "");
530 /* Askfirst shell on tty1-4 */
531 new_init_action(ASKFIRST, bb_default_login_shell, "");
532 //TODO: VC_1 instead of ""? "" is console -> ctty problems -> angry users
533 new_init_action(ASKFIRST, bb_default_login_shell, VC_2);
534 new_init_action(ASKFIRST, bb_default_login_shell, VC_3);
535 new_init_action(ASKFIRST, bb_default_login_shell, VC_4);
537 new_init_action(SYSINIT, INIT_SCRIPT, "");
541 #if ENABLE_FEATURE_USE_INITTAB
542 /* optional_tty:ignored_runlevel:action:command
543 * Delims are not to be collapsed and need exactly 4 tokens
545 while (config_read(parser, token, 4, 0, "#:",
546 PARSE_NORMAL & ~(PARSE_TRIM | PARSE_COLLAPSE))) {
547 /* order must correspond to SYSINIT..RESTART constants */
548 static const char actions[] ALIGN1 =
549 "sysinit\0""wait\0""once\0""respawn\0""askfirst\0"
550 "ctrlaltdel\0""shutdown\0""restart\0";
552 char *tty = token[0];
554 if (!token[3]) /* less than 4 tokens */
556 action = index_in_strings(actions, token[2]);
557 if (action < 0 || !token[3][0]) /* token[3]: command */
559 /* turn .*TTY -> /dev/TTY */
561 if (strncmp(tty, "/dev/", 5) == 0)
563 tty = concat_path_file("/dev/", tty);
565 new_init_action(1 << action, token[3], tty);
570 message(L_LOG | L_CONSOLE, "Bad inittab entry at line %d",
573 config_close(parser);
577 static void pause_and_low_level_reboot(unsigned magic) NORETURN;
578 static void pause_and_low_level_reboot(unsigned magic)
582 /* Allow time for last message to reach serial console, etc */
585 /* We have to fork here, since the kernel calls do_exit(EXIT_SUCCESS)
586 * in linux/kernel/sys.c, which can cause the machine to panic when
587 * the init process exits... */
589 if (pid == 0) { /* child */
597 static void run_shutdown_and_kill_processes(void)
599 /* Run everything to be run at "shutdown". This is done _prior_
600 * to killing everything, in case people wish to use scripts to
601 * shut things down gracefully... */
602 run_actions(SHUTDOWN);
604 message(L_CONSOLE | L_LOG, "The system is going down NOW!");
606 /* Send signals to every process _except_ pid 1 */
608 message(L_CONSOLE | L_LOG, "Sent SIG%s to all processes", "TERM");
613 message(L_CONSOLE, "Sent SIG%s to all processes", "KILL");
615 /*sleep(1); - callers take care about making a pause */
618 /* Signal handling by init:
620 * For process with PID==1, on entry kernel sets all signals to SIG_DFL
621 * and unmasks all signals. However, for process with PID==1,
622 * default action (SIG_DFL) on any signal is to ignore it,
623 * even for special signals SIGKILL and SIGCONT.
624 * Also, any signal can be caught or blocked.
625 * (but SIGSTOP is still handled specially, at least in 2.6.20)
627 * We install two kinds of handlers, "immediate" and "delayed".
629 * Immediate handlers execute at any time, even while, say, sysinit
632 * Delayed handlers just set a flag variable. The variable is checked
633 * in the main loop and acted upon.
635 * halt/poweroff/reboot and restart have immediate handlers.
636 * They only traverse linked list of struct action's, never modify it,
637 * this should be safe to do even in signal handler. Also they
640 * SIGSTOP and SIGTSTP have immediate handlers. They just wait
641 * for SIGCONT to happen.
643 * SIGHUP has a delayed handler, because modifying linked list
644 * of struct action's from a signal handler while it is manipulated
645 * by the program may be disastrous.
647 * Ctrl-Alt-Del has a delayed handler. Not a must, but allowing
648 * it to happen even somewhere inside "sysinit" would be a bit awkward.
650 * There is a tiny probability that SIGHUP and Ctrl-Alt-Del will collide
651 * and only one will be remembered and acted upon.
654 static void halt_reboot_pwoff(int sig) NORETURN;
655 static void halt_reboot_pwoff(int sig)
660 run_shutdown_and_kill_processes();
664 if (sig == SIGTERM) {
667 } else if (sig == SIGUSR2) {
671 message(L_CONSOLE, "Requesting system %s", m);
672 pause_and_low_level_reboot(rb);
676 /* The SIGSTOP/SIGTSTP handler
677 * NB: inside it, all signals except SIGCONT are masked
678 * via appropriate setup in sigaction().
680 static void stop_handler(int sig UNUSED_PARAM)
682 smallint saved_bb_got_signal;
685 saved_bb_got_signal = bb_got_signal;
687 signal(SIGCONT, record_signo);
692 if (bb_got_signal == SIGCONT)
694 /* NB: this can accidentally wait() for a process
695 * which we waitfor() elsewhere! waitfor() must have
696 * code which is resilient against this.
698 wpid = wait_any_nohang(NULL);
699 mark_terminated(wpid);
703 signal(SIGCONT, SIG_DFL);
705 bb_got_signal = saved_bb_got_signal;
708 /* Handler for QUIT - exec "restart" action,
709 * else (no such action defined) do nothing */
710 static void restart_handler(int sig UNUSED_PARAM)
712 struct init_action *a;
714 for (a = init_action_list; a; a = a->next) {
715 if (!(a->action_type & RESTART))
718 /* Starting from here, we won't return.
719 * Thus don't need to worry about preserving errno
722 run_shutdown_and_kill_processes();
724 /* Allow Ctrl-Alt-Del to reboot the system.
725 * This is how kernel sets it up for init, we follow suit.
727 reboot(RB_ENABLE_CAD); /* misnomer */
729 if (open_stdio_to_tty(a->terminal)) {
730 dbg_message(L_CONSOLE, "Trying to re-exec %s", a->command);
731 /* Theoretically should be safe.
732 * But in practice, kernel bugs may leave
733 * unkillable processes, and wait() may block forever.
734 * Oh well. Hoping "new" init won't be too surprised
735 * by having children it didn't create.
737 //while (wait(NULL) > 0)
739 init_exec(a->command);
741 /* Open or exec failed */
742 pause_and_low_level_reboot(RB_HALT_SYSTEM);
747 #if ENABLE_FEATURE_USE_INITTAB
748 static void reload_inittab(void)
750 struct init_action *a, **nextp;
752 message(L_LOG, "reloading /etc/inittab");
754 /* Disable old entries */
755 for (a = init_action_list; a; a = a->next)
758 /* Append new entries, or modify existing entries
759 * (incl. setting a->action_type) if cmd and device name
760 * match new ones. End result: only entries with
761 * a->action_type == 0 are stale.
765 #if ENABLE_FEATURE_KILL_REMOVED
766 /* Kill stale entries */
767 /* Be nice and send SIGTERM first */
768 for (a = init_action_list; a; a = a->next)
769 if (a->action_type == 0 && a->pid != 0)
770 kill(a->pid, SIGTERM);
771 if (CONFIG_FEATURE_KILL_DELAY) {
772 /* NB: parent will wait in NOMMU case */
773 if ((BB_MMU ? fork() : vfork()) == 0) { /* child */
774 sleep(CONFIG_FEATURE_KILL_DELAY);
775 for (a = init_action_list; a; a = a->next)
776 if (a->action_type == 0 && a->pid != 0)
777 kill(a->pid, SIGKILL);
783 /* Remove stale entries and SYSINIT entries.
784 * We never rerun SYSINIT entries anyway,
785 * removing them too saves a few bytes */
786 nextp = &init_action_list;
787 while ((a = *nextp) != NULL) {
788 if ((a->action_type & ~SYSINIT) == 0) {
797 /* run_actions(RESPAWN | ASKFIRST); */
798 /* - we return to main loop, which does this automagically */
802 static int check_delayed_sigs(void)
807 smallint sig = bb_got_signal;
813 #if ENABLE_FEATURE_USE_INITTAB
818 run_actions(CTRLALTDEL);
822 int init_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
823 int init_main(int argc UNUSED_PARAM, char **argv)
825 die_sleep = 30 * 24*60*60; /* if xmalloc would ever die... */
827 if (argv[1] && !strcmp(argv[1], "-q")) {
828 return kill(1, SIGHUP);
832 /* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
834 && (!ENABLE_FEATURE_INITRD || !strstr(applet_name, "linuxrc"))
838 /* Turn off rebooting via CTL-ALT-DEL - we get a
839 * SIGINT on CAD so we can shut things down gracefully... */
840 reboot(RB_DISABLE_CAD); /* misnomer */
843 /* Figure out where the default console should be */
849 /* Make sure environs is set to something sane */
850 putenv((char *) "HOME=/");
851 putenv((char *) bb_PATH_root_path);
852 putenv((char *) "SHELL=/bin/sh");
853 putenv((char *) "USER=root"); /* needed? why? */
856 xsetenv("RUNLEVEL", argv[1]);
858 #if ENABLE_FEATURE_EXTRA_QUIET
860 message(L_CONSOLE | L_LOG, "init started: %s", bb_banner);
863 /* Make sure there is enough memory to do something useful. */
864 if (ENABLE_SWAPONOFF) {
867 if (sysinfo(&info) == 0
868 && (info.mem_unit ? info.mem_unit : 1) * (long long)info.totalram < 1024*1024
870 message(L_CONSOLE, "Low memory, forcing swapon");
871 /* swapon -a requires /proc typically */
872 new_init_action(SYSINIT, "mount -t proc proc /proc", "");
873 /* Try to turn on swap */
874 new_init_action(SYSINIT, "swapon -a", "");
875 run_actions(SYSINIT); /* wait and removing */
879 /* Check if we are supposed to be in single user mode */
881 && (!strcmp(argv[1], "single") || !strcmp(argv[1], "-s") || LONE_CHAR(argv[1], '1'))
883 /* ??? shouldn't we set RUNLEVEL="b" here? */
884 /* Start a shell on console */
885 new_init_action(RESPAWN, bb_default_login_shell, "");
887 /* Not in single user mode - see what inittab says */
889 /* NOTE that if CONFIG_FEATURE_USE_INITTAB is NOT defined,
890 * then parse_inittab() simply adds in some default
891 * actions(i.e., INIT_SCRIPT and a pair
892 * of "askfirst" shells */
897 if (getenv("SELINUX_INIT") == NULL) {
900 putenv((char*)"SELINUX_INIT=YES");
901 if (selinux_init_load_policy(&enforce) == 0) {
902 BB_EXECVP(argv[0], argv);
903 } else if (enforce > 0) {
904 /* SELinux in enforcing mode but load_policy failed */
905 message(L_CONSOLE, "can't load SELinux Policy. "
906 "Machine is in enforcing mode. Halting now.");
912 /* Make the command line just say "init" - thats all, nothing else */
913 strncpy(argv[0], "init", strlen(argv[0]));
914 /* Wipe argv[1]-argv[N] so they don't clutter the ps listing */
916 memset(*argv, 0, strlen(*argv));
918 /* Set up signal handlers */
923 + (1 << SIGUSR1) /* halt */
924 + (1 << SIGTERM) /* reboot */
925 + (1 << SIGUSR2) /* poweroff */
926 , halt_reboot_pwoff);
927 signal(SIGQUIT, restart_handler); /* re-exec another init */
929 /* Stop handler must allow only SIGCONT inside itself */
930 memset(&sa, 0, sizeof(sa));
931 sigfillset(&sa.sa_mask);
932 sigdelset(&sa.sa_mask, SIGCONT);
933 sa.sa_handler = stop_handler;
934 /* NB: sa_flags doesn't have SA_RESTART.
935 * It must be able to interrupt wait().
937 sigaction_set(SIGTSTP, &sa); /* pause */
938 /* Does not work as intended, at least in 2.6.20.
939 * SIGSTOP is simply ignored by init:
941 sigaction_set(SIGSTOP, &sa); /* pause */
943 /* SIGINT (Ctrl-Alt-Del) must interrupt wait(),
944 * setting handler without SA_RESTART flag.
946 bb_signals_recursive_norestart((1 << SIGINT), record_signo);
949 /* Set up "reread /etc/inittab" handler.
950 * Handler is set up without SA_RESTART, it will interrupt syscalls.
952 if (!DEBUG_INIT && ENABLE_FEATURE_USE_INITTAB)
953 bb_signals_recursive_norestart((1 << SIGHUP), record_signo);
955 /* Now run everything that needs to be run */
956 /* First run the sysinit command */
957 run_actions(SYSINIT);
958 check_delayed_sigs();
959 /* Next run anything that wants to block */
961 check_delayed_sigs();
962 /* Next run anything to be run only once */
965 /* Now run the looping stuff for the rest of forever.
970 maybe_WNOHANG = check_delayed_sigs();
972 /* (Re)run the respawn/askfirst stuff */
973 run_actions(RESPAWN | ASKFIRST);
974 maybe_WNOHANG |= check_delayed_sigs();
976 /* Don't consume all CPU time - sleep a bit */
978 maybe_WNOHANG |= check_delayed_sigs();
980 /* Wait for any child process(es) to exit.
982 * If check_delayed_sigs above reported that a signal
983 * was caught, wait will be nonblocking. This ensures
984 * that if SIGHUP has reloaded inittab, respawn and askfirst
985 * actions will not be delayed until next child death.
988 maybe_WNOHANG = WNOHANG;
991 struct init_action *a;
993 /* If signals happen _in_ the wait, they interrupt it,
994 * bb_signals_recursive_norestart set them up that way
996 wpid = waitpid(-1, NULL, maybe_WNOHANG);
1000 a = mark_terminated(wpid);
1002 message(L_LOG, "process '%s' (pid %d) exited. "
1003 "Scheduling for restart.",
1006 /* See if anyone else is waiting to be reaped */
1007 maybe_WNOHANG = WNOHANG;