xref: /original-bsd/sbin/reboot/halt.c (revision c35f7ea3)
1 static	char *sccsid = "@(#)halt.c	4.5 (Berkeley) 04/17/81";
2 /*
3  * Halt
4  */
5 #include <stdio.h>
6 #include <sys/reboot.h>
7 #include <sys/types.h>
8 #include <time.h>
9 #include <errno.h>
10 #include <signal.h>
11 
12 #define SHUTDOWNLOG "/usr/adm/shutdownlog"
13 
14 main(argc, argv)
15 	int argc;
16 	char **argv;
17 {
18 	int howto;
19 	char *ttyn = (char *)ttyname(2);
20 	register i;
21 	register qflag;
22 
23 	howto = RB_HALT;
24 	argc--, argv++;
25 	while (argc > 0) {
26 		if (!strcmp(*argv, "-n"))
27 			howto |= RB_NOSYNC;
28 		else if (!strcmp(*argv, "-y"))
29 			ttyn = 0;
30 		else if (!strcmp(*argv, "-q"))
31 			qflag++;
32 		else {
33 			fprintf(stderr, "usage: halt [ -n ]\n");
34 			exit(1);
35 		}
36 		argc--, argv++;
37 	}
38 	if (ttyn && *(ttyn+strlen("/dev/tty")) == 'd') {
39 		fprintf(stderr, "halt: dangerous on a dialup; use ``halt -y'' if you are really sure\n");
40 		exit(1);
41 	}
42 
43 	if (kill(1, SIGTSTP) == -1) {
44 		fprintf(stderr, "reboot: can't idle init\n");
45 		exit(1);
46 	}
47 
48 	if (!qflag) for (i = 1; ; i++) {
49 		if (kill(-1, SIGKILL) == -1) {
50 			extern int errno;
51 
52 			if (errno == ESRCH)
53 				break;
54 
55 			perror("reboot: kill");
56 			kill(1, SIGHUP);
57 			exit(1);
58 		}
59 		if (i > 5) {
60 	fprintf(stderr, "CAUTION: some process(es) wouldn't die\n");
61 			break;
62 		}
63 		setalarm(2 * i);
64 		pause();
65 	}
66 
67 	if ((howto & RB_NOSYNC) == 0)
68 		log_entry();
69 	if (!qflag) {
70 		if ((howto & RB_NOSYNC)==0) {
71 			markdown();
72 			sync();
73 			sync();
74 		}
75 		setalarm(5);
76 		pause();
77 	}
78 	syscall(55, howto);
79 	perror("reboot");
80 }
81 
82 dingdong()
83 {
84 	/* RRRIIINNNGGG RRRIIINNNGGG */
85 }
86 
87 setalarm(n)
88 {
89 	signal(SIGALRM, dingdong);
90 	alarm(n);
91 }
92 
93 #include <utmp.h>
94 #define SCPYN(a, b)	strncpy(a, b, sizeof(a))
95 char	wtmpf[]	= "/usr/adm/wtmp";
96 struct utmp wtmp;
97 
98 markdown()
99 {
100 	register f = open(wtmpf, 1);
101 	if (f >= 0) {
102 		lseek(f, 0L, 2);
103 		SCPYN(wtmp.ut_line, "~");
104 		SCPYN(wtmp.ut_name, "shutdown");
105 		time(&wtmp.ut_time);
106 		write(f, (char *)&wtmp, sizeof(wtmp));
107 		close(f);
108 	}
109 }
110 
111 char *days[] = {
112 	"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
113 };
114 
115 char *months[] = {
116 	"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
117 	"Oct", "Nov", "Dec"
118 };
119 
120 log_entry()
121 {
122 	FILE *fp;
123 	struct tm *tm, *localtime();
124 	time_t now;
125 
126 	time(&now);
127 	tm = localtime(&now);
128 	fp = fopen(SHUTDOWNLOG, "a");
129 	if (fp == NULL)
130 		return;
131 	fseek(fp, 0L, 2);
132 	fprintf(fp, "%02d:%02d  %s %s %2d, %4d.  Halted.\n", tm->tm_hour,
133 		tm->tm_min, days[tm->tm_wday], months[tm->tm_mon],
134 		tm->tm_mday, tm->tm_year + 1900);
135 	fclose(fp);
136 }
137