--- a/init/halt.c +++ b/init/halt.c @@ -93,6 +93,8 @@ #include "libbb.h" #include "reboot.h" +#include +#include #if ENABLE_FEATURE_WTMP #include @@ -119,6 +121,49 @@ #define write_wtmp() ((void)0) #endif + +static volatile int caught_sigterm = FALSE; +static void signal_handler(int sig) +{ + bb_error_msg("Caught signal %d", sig); + + if (sig == SIGTERM) + caught_sigterm = TRUE; +} + +static int reboot_with_arg(const char *arg) +{ + struct sigaction sa; + int pid; + + /* Fork new thread to handle reboot */ + if ((pid = fork())) + return pid < 0 ? pid : 0; + + /* Handle signal and reboot in child thread */ + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + sa.sa_handler = signal_handler; + sigaction_set(SIGTERM, &sa); + + bb_error_msg("Waiting for SIGTERM"); + + /* The init will send SIGTERM to us after SHUTDOWN actions */ + while (!caught_sigterm) + usleep(50000); + + bb_error_msg("Ready to reboot"); + + /* Wait 200ms for other processes to exit */ + usleep(200000); + sync(); + + bb_error_msg("Rebooting with arg(%s)", arg); + return syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, + LINUX_REBOOT_MAGIC2, + LINUX_REBOOT_CMD_RESTART2, arg); +} + #if ENABLE_FEATURE_WAIT_FOR_INIT /* In Linux, "poweroff" may be spawned even before init. * For example, with ACPI: @@ -239,6 +284,11 @@ CONFIG_TELINIT_PATH); } } + + /* Handle rebooting with arg */ + if (signals[which] == SIGTERM && argc > 1 && argv[1][0] != '-') + rc = reboot_with_arg(argv[1]); + } else { rc = reboot(magic[which]); }