unix/fiss

src/halt/halt.c in master
Repositories | Summary | Log | Files | LICENSE

halt.c (1416B) download


 1#include "util.h"
 2#include "wtmp.h"
 3
 4#include <errno.h>
 5#include <stdbool.h>
 6#include <string.h>
 7#include <sys/reboot.h>
 8#include <unistd.h>
 9
10
11const char* current_prog(void) {
12	return "halt";
13}
14
15int main(int argc, char* argv[]) {
16	bool do_sync  = true,
17	     do_force = false,
18	     do_wtmp  = true,
19	     noop     = false;
20	int         opt;
21	int         rebootnum;
22	const char* initarg;
23
24	char* prog = progname(argv[0]);
25
26	if (streq(prog, "halt")) {
27		rebootnum = RB_HALT_SYSTEM;
28		initarg   = "0";
29	} else if (streq(prog, "poweroff")) {
30		rebootnum = RB_POWER_OFF;
31		initarg   = "0";
32	} else if (streq(prog, "reboot")) {
33		rebootnum = RB_AUTOBOOT;
34		initarg   = "6";
35	} else {
36		fprint(1, "invalid mode: %s\n", prog);
37		return 1;
38	}
39
40	while ((opt = getopt(argc, argv, "dfhinwB")) != -1)
41		switch (opt) {
42			case 'n':
43				do_sync = 0;
44				break;
45			case 'w':
46				noop    = 1;
47				do_sync = 0;
48				break;
49			case 'd':
50				do_wtmp = 0;
51				break;
52			case 'h':
53			case 'i':
54				/* silently ignored.  */
55				break;
56			case 'f':
57				do_force = 1;
58				break;
59			case 'B':
60				write_wtmp(1);
61				return 0;
62			default:
63				fprint(1, "Usage: %s [-n] [-f] [-d] [-w] [-B]", prog);
64				return 1;
65		}
66
67	if (do_wtmp)
68		write_wtmp(0);
69
70	if (do_sync)
71		sync();
72
73	if (!noop) {
74		if (do_force) {
75			reboot(rebootnum);
76		} else {
77			execl("/sbin/init", "init", initarg, NULL);
78		}
79		fprint(1, "reboot failed: %r\n");
80	}
81
82	return 0;
83}