1 
2 #include <err.h>
3 #include <limits.h>
4 #include "xenctrl.h"
5 #include <sys/types.h>
6 #include <sys/stat.h>
7 #include <fcntl.h>
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <signal.h>
11 #include <stdio.h>
12 
13 xc_interface *h;
14 int id = 0;
15 
daemonize(void)16 void daemonize(void)
17 {
18     switch (fork()) {
19     case -1:
20 	err(1, "fork");
21     case 0:
22 	break;
23     default:
24 	exit(0);
25     }
26     umask(0);
27     if (setsid() < 0)
28 	err(1, "setsid");
29     if (chdir("/") < 0)
30 	err(1, "chdir /");
31     if (freopen("/dev/null", "r", stdin) == NULL)
32         err(1, "reopen stdin");
33     if(freopen("/dev/null", "w", stdout) == NULL)
34         err(1, "reopen stdout");
35     if(freopen("/dev/null", "w", stderr) == NULL)
36         err(1, "reopen stderr");
37 }
38 
catch_exit(int sig)39 void catch_exit(int sig)
40 {
41     if (id)
42         xc_watchdog(h, id, 300);
43     exit(0);
44 }
45 
catch_usr1(int sig)46 void catch_usr1(int sig)
47 {
48     if (id)
49         xc_watchdog(h, id, 0);
50     exit(0);
51 }
52 
main(int argc,char ** argv)53 int main(int argc, char **argv)
54 {
55     int t, s;
56     int ret;
57 
58     if (argc < 2)
59 	errx(1, "usage: %s <timeout> <sleep>", argv[0]);
60 
61     daemonize();
62 
63     h = xc_interface_open(NULL, NULL, 0);
64     if (h == NULL)
65 	err(1, "xc_interface_open");
66 
67     t = strtoul(argv[1], NULL, 0);
68     if (t == ULONG_MAX)
69 	err(1, "strtoul");
70 
71     s = t / 2;
72     if (argc == 3) {
73 	s = strtoul(argv[2], NULL, 0);
74 	if (s == ULONG_MAX)
75 	    err(1, "strtoul");
76     }
77 
78     if (signal(SIGHUP, &catch_exit) == SIG_ERR)
79 	err(1, "signal");
80     if (signal(SIGINT, &catch_exit) == SIG_ERR)
81 	err(1, "signal");
82     if (signal(SIGQUIT, &catch_exit) == SIG_ERR)
83 	err(1, "signal");
84     if (signal(SIGTERM, &catch_exit) == SIG_ERR)
85 	err(1, "signal");
86     if (signal(SIGUSR1, &catch_usr1) == SIG_ERR)
87 	err(1, "signal");
88 
89     id = xc_watchdog(h, 0, t);
90     if (id <= 0)
91         err(1, "xc_watchdog setup");
92 
93     for (;;) {
94         sleep(s);
95         ret = xc_watchdog(h, id, t);
96         if (ret != 0)
97             err(1, "xc_watchdog");
98     }
99 }
100