2 * UCW Library -- Daemon Control
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.
11 #include <ucw/daemon.h>
12 #include <ucw/process.h>
24 static enum daemon_control_status
25 daemon_control_err(struct daemon_control_params *dc, char *msg, ...)
29 vsnprintf(dc->error_msg, DAEMON_ERR_LEN, msg, args);
31 return DAEMON_STATUS_ERROR;
35 daemon_read_pid(struct daemon_control_params *dc, int will_wait)
37 int pid_fd = open(dc->pid_file, O_RDONLY);
42 daemon_control_err(dc, "Cannot open PID file `%s': %m", dc->pid_file);
46 if (flock(pid_fd, LOCK_EX | (will_wait ? 0 : LOCK_NB)) >= 0)
48 // The lock file is stale
53 if (errno != EINTR && errno != EWOULDBLOCK)
55 daemon_control_err(dc, "Cannot lock PID file `%s': %m", dc->pid_file);
60 int n = read(pid_fd, buf, sizeof(buf));
63 daemon_control_err(dc, "Error reading `%s': %m", dc->pid_file);
66 if (n == (int) sizeof(buf))
68 daemon_control_err(dc, "PID file `%s' is too long", dc->pid_file);
75 daemon_control_err(dc, "PID file `%s' does not contain a valid PID", dc->pid_file);
86 enum daemon_control_status
87 daemon_control(struct daemon_control_params *dc)
89 enum daemon_control_status st = DAEMON_STATUS_ERROR;
92 int guard_fd = open(dc->guard_file, O_RDWR | O_CREAT, 0666);
94 return daemon_control_err(dc, "Cannot open guard file `%s': %m", dc->guard_file);
95 if (flock(guard_fd, LOCK_EX) < 0)
96 return daemon_control_err(dc, "Cannot lock guard file `%s': %m", dc->guard_file);
99 int pid = daemon_read_pid(dc, 0);
105 case DAEMON_CONTROL_CHECK:
107 st = DAEMON_STATUS_OK;
109 st = DAEMON_STATUS_NOT_RUNNING;
111 case DAEMON_CONTROL_START:
113 st = DAEMON_STATUS_ALREADY_DONE;
119 daemon_control_err(dc, "Cannot fork: %m");
125 execvp(dc->argv[0], dc->argv);
126 fprintf(stderr, "Cannot execute `%s': %m\n", dc->argv[0]);
127 exit(DAEMON_STATUS_ERROR);
130 int ec = waitpid(pp, &stat, 0);
133 daemon_control_err(dc, "Cannot wait: %m");
136 if (WIFEXITED(stat) && WEXITSTATUS(stat) == DAEMON_STATUS_ERROR)
138 daemon_control_err(dc, "Cannot execute the daemon");
141 char ecmsg[EXIT_STATUS_MSG_SIZE];
142 if (format_exit_status(ecmsg, stat))
144 daemon_control_err(dc, "Daemon %s %s", dc->argv[0], ecmsg);
147 pid = daemon_read_pid(dc, 0);
149 daemon_control_err(dc, "Daemon %s failed to write the PID file `%s'", dc->argv[0], dc->pid_file);
151 st = DAEMON_STATUS_OK;
154 case DAEMON_CONTROL_STOP:
156 return DAEMON_STATUS_ALREADY_DONE;
157 sig = dc->signal ? : SIGTERM;
158 if (kill(pid, sig) < 0)
160 daemon_control_err(dc, "Cannot send signal %d: %m", sig);
163 pid = daemon_read_pid(dc, 1);
166 st = DAEMON_STATUS_OK;
168 case DAEMON_CONTROL_SIGNAL:
170 return DAEMON_STATUS_NOT_RUNNING;
171 sig = dc->signal ? : SIGHUP;
172 if (kill(pid, sig) < 0)
173 daemon_control_err(dc, "Cannot send signal %d: %m", sig);
175 st = DAEMON_STATUS_OK;