diff --git a/src/daemonitor/999_main.c b/src/daemonitor/999_main.c index cc8f831..2f26243 100644 --- a/src/daemonitor/999_main.c +++ b/src/daemonitor/999_main.c @@ -7,6 +7,14 @@ +/* DEFAULT_RESTART_INTERVAL + * The default argument to --restart-interval, in seconds. + */ +#define DEFAULT_RESTART_INTERVAL 10 +#define DEFAULT_RESTART_INTERVAL_S "10" + + + /* usage() * Display the usage info. */ @@ -24,6 +32,9 @@ void usage(void) " STDERR - log to stderr (default)\n" " file path - log to file\n" " -p, --pidfile Write PID to file.\n" + " -R, --restart-interval Sets the length of time between the process\n" + " exiting and being restarted, in seconds (default\n" + " " DEFAULT_RESTART_INTERVAL_S "). May be 0 to restart immediately.\n" "", stderr); } @@ -38,6 +49,7 @@ struct option options[] = { { "daemon", no_argument, 0, 'd' }, { "log", required_argument, 0, 'l' }, { "pidfile", required_argument, 0, 'p' }, + { "restart-interval", required_argument, 0, 'R' }, { 0, 0, 0, 0 } }; @@ -46,7 +58,7 @@ struct option options[] = { /* optstr * The list of short commandline options for getopt(3). Sorted alphabetically, lowercase first. */ -const char* optstr = "dhl:p:V"; +const char* optstr = "dhl:p:R:V"; @@ -56,8 +68,9 @@ const char* optstr = "dhl:p:V"; */ int main(int argc, char* argv[]) { - const char* log_argument = 0, * pidfile_argument = 0; - int daemon = 0; + char* endp; + const char* log_argument = 0, * pidfile_argument = 0, * restart_argument = 0; + int daemon = 0, restart_interval = DEFAULT_RESTART_INTERVAL; /* safety */ close_file_descriptors(); /* leaves stdout etc. open */ @@ -72,9 +85,24 @@ int main(int argc, char* argv[]) case 'd': ++daemon; break; case 'l': log_argument = optarg; break; case 'p': pidfile_argument = optarg; break; + case 'R': restart_argument = optarg; break; } } opts_done: + if(restart_argument) { + restart_interval = strtol(restart_argument, &endp, 0); + if(*endp || restart_interval < 0) { + LOG_ANYWHERE("Invalid --restart-interval option `%s'. Must be an integer >= 0.", + restart_argument); + return 1; + } + } + + if(optind >= argc) { + LOG_ANYWHERE("Program not specified."); + return 1; + } + /* set up logging */ if(!log_argument || !strcmp(log_argument, "STDERR")) { log_destination_set(log_destination_stderr); @@ -102,6 +130,16 @@ int main(int argc, char* argv[]) } } + /* run process */ + while(1) { + run_program(argv + optind, argc - optind); + + if(restart_interval) { + LOG(LOG_NOTICE, "Sleeping for %d seconds.", restart_interval); + safe_sleep_fixed(restart_interval, 0); + } + } + return 0; }