f3627f206bfae8a69b47ca734b03bdae68df66db
[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 GPLv2 or later, see file LICENSE in this tarball for details.
8  */
9
10 #include <signal.h>
11 #include <sys/reboot.h>
12 #include "busybox.h"
13
14 #include <unistd.h>
15
16 int halt_main(int argc, char *argv[])
17 {
18         static const int magic[] = {
19 #ifdef RB_HALT_SYSTEM
20 RB_HALT_SYSTEM,
21 #elif defined RB_HALT
22 RB_HALT,
23 #endif
24 #ifdef RB_POWER_OFF
25 RB_POWER_OFF,
26 #elif defined RB_POWERDOWN
27 RB_POWERDOWN,
28 #endif
29 RB_AUTOBOOT
30         };
31         static const int signals[] = {SIGUSR1, SIGUSR2, SIGTERM};
32
33         char *delay = "hpr";
34         int which, flags, rc = 1;
35
36         /* Figure out which applet we're running */
37         for(which=0;delay[which]!=*bb_applet_name;which++);
38
39         /* Parse and handle arguments */
40         flags = bb_getopt_ulflags(argc, argv, "d:nf", &delay);
41         if (flags&1) sleep(atoi(delay));
42         if (!(flags&2)) sync();
43         
44         /* Perform action. */
45         if (ENABLE_INIT && !(flags & 4)) {
46                 if (ENABLE_FEATURE_INITRD) {
47                         long *pidlist=find_pid_by_name("linuxrc");
48                         if (*pidlist>0) rc = kill(*pidlist,signals[which]);
49                         if (ENABLE_FEATURE_CLEAN_UP) free(pidlist);
50                 }
51                 if (rc) rc = kill(1,signals[which]);
52         } else rc = reboot(magic[which]);
53
54         if (rc) bb_error_msg("No.");
55         return rc;
56 }