Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ Options:
-a, --attempts <n> retry attempts within 60 seconds [10]
-R, --on-restart <cmd> execute <cmd> on restarts
-E, --on-error <cmd> execute <cmd> on error
-X, --on-exit <cmd> execute <cmd> on monitor exit

```

Expand Down
27 changes: 27 additions & 0 deletions src/mon.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
*/
Expand All @@ -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);
}
Expand Down Expand Up @@ -478,6 +493,16 @@ on_error(command_t *self) {
monitor->on_error = self->arg;
}

/*
* --on-exit <cmd>
*/

static void
on_mon_exit(command_t *self) {
monitor_t *monitor = (monitor_t *) self->data;
monitor->on_exit = self->arg;
}

/*
* --attempts <n>
*/
Expand All @@ -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;
Expand All @@ -521,6 +547,7 @@ main(int argc, char **argv){
command_option(&program, "-a", "--attempts <n>", "retry attempts within 60 seconds [10]", on_attempts);
command_option(&program, "-R", "--on-restart <cmd>", "execute <cmd> on restarts", on_restart);
command_option(&program, "-E", "--on-error <cmd>", "execute <cmd> on error", on_error);
command_option(&program, "-X", "--on-exit <cmd>", "execute <cmd> on monitor exit", on_mon_exit);
command_parse(&program, argc, argv);

if (monitor.show_status) {
Expand Down