2 * UCW Library -- Daemonization
4 * (c) 2012 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
13 #include <sys/types.h>
15 /** Parameters passed to the daemon helper. **/
16 struct daemon_params {
17 uns flags; // DAEMON_FLAG_xxx
18 const char *pid_file; // A path to PID file (optional)
19 const char *run_as_user; // User name or "#uid" (optional)
20 const char *run_as_group; // Group name or "#gid" (optional)
30 /** Flags passed to the daemon helper. **/
32 DAEMON_FLAG_PRESERVE_CWD = 1, // Skip chdir("/")
36 * Daemon initialization. Should be run after parsing of options.
37 * It resolves the UID and GID to run with and locks the PID file.
38 * Upon error, it calls @die().
40 void daemon_init(struct daemon_params *dp);
43 * Run the daemon. Should be run when everything is initialized. It forks off
44 * a new process and does all necessary setup. Inside the new process, it calls
45 * @body (and when it returns, it exits the process). In the original process, it writes
46 * the PID file and returns.
48 void daemon_run(struct daemon_params *dp, void (*body)(struct daemon_params *dp));
51 * Clean up when the daemon is about to exit. It removes the PID file.
53 void daemon_exit(struct daemon_params *dp);
55 #define DAEMON_ERR_LEN 256
57 /** Parameters passed to daemon_control() **/
58 struct daemon_control_params {
59 const char *pid_file; // A path to PID file
60 const char *guard_file; // A path to guard file
61 int action; // Action to perform (DAEMON_CONTROL_xxx)
62 char * const *argv; // Daemon's arguments, NULL-terminated (for DAEMON_CONTROL_START)
63 int signal; // Signal to send (for DAEMON_CONTROL_SIGNAL)
64 char error_msg[DAEMON_ERR_LEN]; // A detailed error message returned (for DAEMON_STATUS_ERROR)
67 enum daemon_control_action {
71 DAEMON_CONTROL_SIGNAL,
75 * Perform an action on a daemon:
77 * * `DAEMON_CONTROL_START` to start the daemon
78 * * `DAEMON_CONTROL_STOP` to stop the daemon (send `SIGTERM` or `dc->signal` if non-zero)
79 * * `DAEMON_CONTROL_CHECK` to check that the daemon is running
80 * * `DAEMON_CONTROL_SIGNAL` to send a signal to the daemon
82 * The function returns a status code:
84 * * `DAEMON_STATUS_OK` if the action has been performed successfully
85 * * `DAEMON_STATUS_ALREADY_DONE` if the daemon is already in the requested state
86 * * `DAEMON_STATUS_NOT_RUNNING` if the action failed, because the daemon is not running
87 * * `DAEMON_STATUS_ERROR` if the action failed for some other reason (in this case,
88 * the error_msg field contains a full error message)
90 enum daemon_control_status daemon_control(struct daemon_control_params *dc);
92 enum daemon_control_status {
94 DAEMON_STATUS_ALREADY_DONE = 100,
95 DAEMON_STATUS_NOT_RUNNING = 101,
96 DAEMON_STATUS_ERROR = 102,