From 5b93ce1818e760bd86145aa0a01de4dcdae36f23 Mon Sep 17 00:00:00 2001 From: Mathias Buus Date: Sun, 19 Apr 2015 15:24:27 -0700 Subject: [PATCH] add monitor on-exit hook --- Readme.md | 1 + src/mon.c | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/Readme.md b/Readme.md index ff63265..af7ac39 100644 --- a/Readme.md +++ b/Readme.md @@ -40,6 +40,7 @@ Options: -a, --attempts retry attempts within 60 seconds [10] -R, --on-restart execute on restarts -E, --on-error execute on error + -X, --on-exit execute on monitor exit ``` diff --git a/src/mon.c b/src/mon.c index 5703e7c..7b50239 100644 --- a/src/mon.c +++ b/src/mon.c @@ -43,6 +43,7 @@ typedef struct { const char *logfile; const char *on_error; const char *on_restart; + const char *on_exit; int64_t last_restart_at; int64_t clock; int daemon; @@ -227,6 +228,19 @@ redirect_stdio_to(const char *file) { dup2(logfd, 2); } +/* + * Invoke the --on-exit command. + */ + +void +exec_exit_command(monitor_t *monitor, pid_t pid) { + char buf[1024] = {0}; + snprintf(buf, 1024, "%s %d", monitor->on_exit, pid); + log("on exit `%s`", buf); + int status = system(buf); + if (status) log("exit(%d)", status); +} + /* * Graceful exit, signal process group. */ @@ -240,6 +254,7 @@ graceful_exit(int sig) { kill(-pid, sig); log("waiting for exit"); waitpid(read_pidfile(monitor.pidfile), &status, 0); + if (monitor.on_exit) exec_exit_command(&monitor, pid); log("bye :)"); exit(0); } @@ -478,6 +493,16 @@ on_error(command_t *self) { monitor->on_error = self->arg; } +/* + * --on-exit + */ + +static void +on_mon_exit(command_t *self) { + monitor_t *monitor = (monitor_t *) self->data; + monitor->on_exit = self->arg; +} + /* * --attempts */ @@ -498,6 +523,7 @@ main(int argc, char **argv){ monitor.mon_pidfile = NULL; monitor.on_restart = NULL; monitor.on_error = NULL; + monitor.on_exit = NULL; monitor.logfile = "mon.log"; monitor.daemon = 0; monitor.sleepsec = 1; @@ -521,6 +547,7 @@ main(int argc, char **argv){ command_option(&program, "-a", "--attempts ", "retry attempts within 60 seconds [10]", on_attempts); command_option(&program, "-R", "--on-restart ", "execute on restarts", on_restart); command_option(&program, "-E", "--on-error ", "execute on error", on_error); + command_option(&program, "-X", "--on-exit ", "execute on monitor exit", on_mon_exit); command_parse(&program, argc, argv); if (monitor.show_status) {