e3d77d17eed165a4daeb069cf80f554d059a8fb3
[platform/upstream/busybox.git] / miscutils / watchdog.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini watchdog implementation for busybox
4  *
5  * Copyright (C) 2003  Paul Mundt <lethal@linux-sh.org>
6  * Copyright (C) 2006  Bernhard Fischer <busybox@busybox.net>
7  *
8  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
9  */
10
11 #include "busybox.h"
12
13 #define OPT_FOREGROUND 0x01
14 #define OPT_TIMER      0x02
15
16 static void watchdog_shutdown(int ATTRIBUTE_UNUSED sig) ATTRIBUTE_NORETURN;
17 static void watchdog_shutdown(int ATTRIBUTE_UNUSED sig)
18 {
19         write(3, "V", 1);       /* Magic, see watchdog-api.txt in kernel */
20         if (ENABLE_FEATURE_CLEAN_UP)
21                 close(3);
22         exit(0);
23 }
24
25 int watchdog_main(int argc, char **argv);
26 int watchdog_main(int argc, char **argv)
27 {
28         unsigned opts;
29         unsigned timer_duration = 30; /* Userspace timer duration, in seconds */
30         char *t_arg;
31
32         opts = getopt32(argc, argv, "Ft:", &t_arg);
33
34         if (opts & OPT_TIMER)
35                 timer_duration = xatou(t_arg);
36
37         /* We're only interested in the watchdog device .. */
38         if (optind < argc - 1 || argc == 1)
39                 bb_show_usage();
40
41         if (!(opts & OPT_FOREGROUND)) {
42 #ifdef BB_NOMMU
43                 if (!re_execed)
44                         vfork_daemon_rexec(0, 1, argv);
45 #else
46                 xdaemon(0, 1);
47 #endif
48         }
49
50         signal(SIGHUP, watchdog_shutdown);
51         signal(SIGINT, watchdog_shutdown);
52
53         /* Use known fd # - avoid needing global 'int fd' */
54         dup2(xopen(argv[argc - 1], O_WRONLY), 3);
55
56         while (1) {
57                 /*
58                  * Make sure we clear the counter before sleeping, as the counter value
59                  * is undefined at this point -- PFM
60                  */
61                 write(3, "", 1);
62                 sleep(timer_duration);
63         }
64
65         watchdog_shutdown(0);
66
67         /* return EXIT_SUCCESS; */
68 }