Add/tidy up commandline options

This commit is contained in:
Laurence Withers 2008-07-26 16:47:03 +00:00
parent f2f2baa129
commit 1ff8b24650
1 changed files with 32 additions and 8 deletions

View File

@ -17,11 +17,13 @@ void usage(void)
"Valid options:\n"
" -h, --help Display this screen.\n"
" -V, --version Display version number.\n"
" -d, --daemon Daemonise.\n"
" -l, --log <dest> Log file destination, may be one of:\n"
" SYSLOG - log to syslog (default)\n"
" SYSLOG:name - log to syslog\n"
" STDOUT - log to stdout\n"
" STDERR - log to stderr\n"
" STDERR - log to stderr (default)\n"
" file path - log to file\n"
" -p, --pidfile <path> Write PID to file.\n"
"", stderr);
}
@ -33,7 +35,9 @@ void usage(void)
struct option options[] = {
{ "help", no_argument, 0, 'h' },
{ "version", no_argument, 0, 'V' },
{ "daemon", no_argument, 0, 'd' },
{ "log", required_argument, 0, 'l' },
{ "pidfile", required_argument, 0, 'p' },
{ 0, 0, 0, 0 }
};
@ -42,7 +46,7 @@ struct option options[] = {
/* optstr
* The list of short commandline options for getopt(3). Sorted alphabetically, lowercase first.
*/
const char* optstr = "hl:V";
const char* optstr = "dhl:p:V";
@ -52,25 +56,33 @@ const char* optstr = "hl:V";
*/
int main(int argc, char* argv[])
{
const char* log_argument = 0;
const char* log_argument = 0, * pidfile_argument = 0;
int daemon = 0;
/* safety */
close_file_descriptors(); /* leaves stdout etc. open */
/* parse commandline arguments */
while(1) {
switch(getopt_long(argc, argv, optstr, options, 0)) {
case -1: goto opts_done;
case '?': LOG_ANYWHERE("Invalid commandline options."); return 1;
case 'h': usage(); return 1;
case 'V': fputs("daemonitor " VERSION "\n", stderr); return 1;
case 'd': ++daemon; break;
case 'l': log_argument = optarg; break;
case 'p': pidfile_argument = optarg; break;
}
}
opts_done:
/* set up logging */
if(!log_argument || !strcmp(log_argument, "SYSLOG")) {
log_destination_set(log_destination_syslog);
if(!log_argument || !strcmp(log_argument, "STDERR")) {
log_destination_set(log_destination_stderr);
} else if(!strcmp(log_argument, "STDOUT")) {
log_destination_set(log_destination_stdout);
} else if(!strcmp(log_argument, "STDERR")) {
log_destination_set(log_destination_stderr);
} else if(!strncmp(log_argument, "SYSLOG:", 7)) {
openlog(log_argument + 7, 0, LOG_DAEMON);
log_destination_set(log_destination_syslog);
} else {
if(log_destination_set_file(log_argument)) {
LOG_ANYWHERE("Error logging to file `%s' (%m).", log_argument);
@ -78,6 +90,18 @@ int main(int argc, char* argv[])
}
}
/* daemonise? */
if(daemon) daemonise();
/* write a PID file */
if(pidfile_argument) {
pidfile_set_filename(pidfile_argument);
/* keep retrying until we're done */
while(pidfile_write()) {
safe_sleep_fixed(5, 0);
}
}
return 0;
}