correct fork error handling
[vlock.git] / sysrq.c
blobcaf14059200261735a4a60e07f3ce7081fd5a430
1 /* sysrq.c -- sysrq handling routines for vlock
3 * This program is copyright (C) 2007 Frank Benkstein, and is free
4 * software which is freely distributable under the terms of the
5 * GNU General Public License version 2, included as the file COPYING in this
6 * distribution. It is NOT public domain software, and any
7 * redistribution not permitted by the GNU General Public License is
8 * expressly forbidden without prior written permission from
9 * the author.
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <errno.h>
17 #include <unistd.h>
19 #define OLD_VALUE_LENGTH 8
21 static const char SYSRQ_PATH[] = "/proc/sys/kernel/sysrq";
22 static const char SYSRQ_DISABLE_VALUE[] = "0\n";
24 static FILE *sysrq_file = NULL;
26 static char old_value[OLD_VALUE_LENGTH];
28 int disable_sysrq(void) {
29 sysrq_file = fopen(SYSRQ_PATH, "r+");
31 if (!sysrq_file) {
32 fprintf(stderr, "Warning: couldn't open '%s': %s\n", SYSRQ_PATH, strerror(errno));
33 return 0;
36 if (!fgets(old_value, OLD_VALUE_LENGTH, sysrq_file)) {
37 fprintf(stderr, "Warning: couldn't get current sysrq setting, won't disable sysrq: %s\n", strerror(errno));
38 goto error;
41 rewind(sysrq_file);
43 if (
44 !fputs(SYSRQ_DISABLE_VALUE, sysrq_file)
45 || !(ftruncate(fileno(sysrq_file), ftello(sysrq_file)) == 0)
46 || !(fflush(sysrq_file) == 0)
47 ) {
48 fprintf(stderr, "Warning: couldn't disable sysrq: %s\n", strerror(errno));
49 goto error;
52 rewind(sysrq_file);
54 return 1;
55 error:
56 fclose(sysrq_file);
57 sysrq_file = NULL;
58 return 0;
61 void restore_sysrq(void) {
62 if (!sysrq_file)
63 return;
65 if (!fputs(old_value, sysrq_file)) {
66 fprintf(stderr, "Warning: couldn't restore old sysrq setting: %s\n", strerror(errno));
69 fclose(sysrq_file);
72 void mask_sysrq(void) {
73 if (disable_sysrq())
74 atexit(restore_sysrq);