aboutsummaryrefslogtreecommitdiffstats
path: root/coreupdown.c
diff options
context:
space:
mode:
Diffstat (limited to 'coreupdown.c')
-rw-r--r--coreupdown.c48
1 files changed, 38 insertions, 10 deletions
diff --git a/coreupdown.c b/coreupdown.c
index 403bdf6..70015ec 100644
--- a/coreupdown.c
+++ b/coreupdown.c
@@ -3,6 +3,7 @@
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
+#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
@@ -11,6 +12,7 @@
#include <unistd.h>
static const char *argv0;
+static volatile sig_atomic_t caught_sighup = 0;
#define coreup() coreupdown(ULONG_MAX)
#define coredown() coreupdown(1)
@@ -226,14 +228,25 @@ line_done:
#undef IDLE_FIELD
}
+static void
+sighup_handler(int signo)
+{
+ (void) signo;
+ caught_sighup = 1;
+}
+
static int
-daemon_main(int argc, char **argv)
+daemon_main(int argc, char **argv, int orig_argc, char **orig_argv, int reexeced)
{
uintmax_t total, idle;
size_t cpus;
- int up_time = 0, down_time = 0, cooldown = 0;
+ int up_time = 0, down_time = 0, cooldown = 0, err;
struct timespec interval, rem;
+restart:
+ if (reexeced)
+ argv[0] = "coreupdownd";
+
if (argc && !strcmp(argv[0], "--")) {
argv++;
argc--;
@@ -244,11 +257,14 @@ daemon_main(int argc, char **argv)
return 1;
}
- /* TODO configurations should be configurable */
+ if (!reexeced) {
+ /* TODO add proper daemonisation */
+ }
- /* TODO add SIGHUP support */
+ /* TODO configurations should be configurable */
- /* TODO add proper daemonisation */
+ if (signal(SIGHUP, sighup_handler) == SIG_ERR)
+ fprintf(stderr, "%s: signal SIGHUP <function>: %s\n", argv0, strerror(errno));
interval.tv_sec = DAEMON_INTERVAL_SEC;
interval.tv_nsec = DAEMON_INTERVAL_NSEC;
@@ -260,16 +276,26 @@ daemon_main(int argc, char **argv)
close(STDOUT_FILENO);
for (;;) {
- if (clock_nanosleep(CLOCK_REALTIME /* = monotonic */, 0, &interval, &rem)) {
+ if (caught_sighup) {
+ caught_sighup = 0;
+ orig_argv[0] = "coreupdownd ";
+ execv(DAEMON_PATH, orig_argv);
+ fprintf(stderr, "%s: execv %s: %s\n", argv0, DAEMON_PATH, strerror(errno));
+ reexeced = 1;
+ argv = &orig_argv[1];
+ argc = orig_argc - 1;
+ goto restart;
+ }
+
+ if ((err = clock_nanosleep(CLOCK_REALTIME /* = monotonic */, 0, &interval, &rem))) {
do {
- if (errno != EINTR) {
+ if (err != EINTR) {
fprintf(stderr, "%s: clock_nanosleep CLOCK_REALTIME: %s\n",
argv0, strerror(errno));
return 1;
}
- } while (clock_nanosleep(CLOCK_REALTIME, 0, &rem, &rem));
+ } while ((err = clock_nanosleep(CLOCK_REALTIME, 0, &rem, &rem)));
}
- sleep(1);
if (getusage(&total, &idle, &cpus))
return 1;
if (cooldown) {
@@ -313,7 +339,9 @@ main(int argc, char **argv)
if (!strcmp(command, "coredown"))
return oneshot_main(argc, argv, 1);
if (!strcmp(command, "coreupdownd"))
- return daemon_main(argc, argv);
+ return daemon_main(argc, argv, argc + 1, &argv[-1], 0);
+ if (!strcmp(command, "coreupdownd "))
+ return daemon_main(argc, argv, argc + 1, &argv[-1], 1);
}
fprintf(stderr, "usage: coreup [count]\n"