fix subtle bug inherited from dash
[oweals/busybox.git] / init / halt.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Poweroff reboot and halt, oh my.
4  *
5  * Copyright 2006 by Rob Landley <rob@landley.net>
6  *
7  * Licensed under GPL version 2, see file LICENSE in this tarball for details.
8  */
9
10 #include "busybox.h"
11 #include <sys/reboot.h>
12
13 int halt_main(int argc, char *argv[])
14 {
15         static const int magic[] = {
16 #ifdef RB_HALT_SYSTEM
17 RB_HALT_SYSTEM,
18 #elif defined RB_HALT
19 RB_HALT,
20 #endif
21 #ifdef RB_POWER_OFF
22 RB_POWER_OFF,
23 #elif defined RB_POWERDOWN
24 RB_POWERDOWN,
25 #endif
26 RB_AUTOBOOT
27         };
28         static const int signals[] = { SIGUSR1, SIGUSR2, SIGTERM };
29
30         char *delay;
31         int which, flags, rc = 1;
32
33         /* Figure out which applet we're running */
34         for (which = 0; "hpr"[which] != *applet_name; which++);
35
36         /* Parse and handle arguments */
37         flags = getopt32(argc, argv, "d:nf", &delay);
38         if (flags & 1) sleep(xatou(delay));
39         if (!(flags & 2)) sync();
40
41         /* Perform action. */
42         if (ENABLE_INIT && !(flags & 4)) {
43                 if (ENABLE_FEATURE_INITRD) {
44                         pid_t *pidlist = find_pid_by_name("linuxrc");
45                         if (pidlist[0] > 0)
46                                 rc = kill(pidlist[0], signals[which]);
47                         if (ENABLE_FEATURE_CLEAN_UP)
48                                 free(pidlist);
49                 }
50                 if (rc)
51                         rc = kill(1, signals[which]);
52         } else
53                 rc = reboot(magic[which]);
54
55         if (rc)
56                 bb_error_msg("no");
57         return rc;
58 }