2 * A Simple Utility for Controlling Daemons
4 * (c) 2012 Martin Mares <mj@ucw.cz>
6 * For more information, see ucw/doc/daemon.txt.
15 #include <ucw/daemon.h>
16 #include <ucw/signames.h>
17 #include <ucw/string.h>
27 static struct option options[] = {
28 { "pid-file", required_argument, NULL, 'p' },
29 { "guard-file", required_argument, NULL, 'g' },
30 { "signal", required_argument, NULL, 's' },
31 { "start", no_argument, &action, DAEMON_CONTROL_START },
32 { "stop", no_argument, &action, DAEMON_CONTROL_STOP },
33 { "check", no_argument, &action, DAEMON_CONTROL_CHECK },
34 { "reload", no_argument, &action, DAEMON_CONTROL_SIGNAL },
35 { NULL, no_argument, NULL, 0 }
42 Usage: ucw-daemon-control --start <options> -- <daemon> <args>\n\
43 or: ucw-daemon-control --stop <options>\n\
44 or: ucw-daemon-control --reload <options>\n\
45 or: ucw-daemon-control --check <options>\n\
48 --pid-file <name> Name of PID file for this daemon (mandatory)\n\
49 --guard-file <name> Name of guard file (default: derived from --pid-file)\n\
50 --signal <sig> Send a signal of a given name or number\n\
51 Default: SIGTERM for --stop, SIGHUP for --reload\n\
54 0 Successfully completed\n\
55 1 Invalid arguments\n\
56 100 The action was null (e.g., --stop on a stopped daemon)\n\
57 101 The daemon was not running (on --reload or --check)\n\
58 102 The action has failed (error message was printed to stderr)\n\
59 103 The daemon was in an undefined state (e.g., stale PID file)\n\
65 main(int argc, char **argv)
68 struct daemon_control_params dc = { };
70 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0)
79 dc.guard_file = optarg;
82 sig = sig_name_to_number(optarg);
85 fprintf(stderr, "%s: Unknown signal %s\n", argv[0], optarg);
93 if (!dc.pid_file || !action)
97 if (action == DAEMON_CONTROL_START)
101 dc.argv = argv + optind;
103 else if (optind < argc)
108 if (!str_has_suffix(dc.pid_file, ".pid"))
110 fprintf(stderr, "%s: For automatic choice of --guard-file, the --pid-file must end with `.pid'\n", argv[0]);
113 int len = strlen(dc.pid_file);
114 char *buf = xmalloc(len + 2);
115 sprintf(buf, "%.*s.lock", len-4, dc.pid_file);
119 int err = daemon_control(&dc);
120 if (err == DAEMON_STATUS_ERROR)
121 fprintf(stderr, "%s: %s\n", argv[0], dc.error_msg);