int pidfile_open(const char *name)
{
- struct flock lock;
- p_clear(&lock, 1);
- lock.l_type = F_WRLCK;
if (name) {
pidfile = fopen(name, "w");
if (!pidfile)
return -1;
- if (fcntl(fileno(pidfile), F_SETLK, &lock) == -1) {
- crit("program already started");
- fclose(pidfile);
- pidfile = NULL;
- return -1;
- }
fprintf(pidfile, "%d\n", getpid());
return fflush(pidfile);
}
static void pidfile_close(void)
{
- struct flock lock;
- p_clear(&lock, 1);
- lock.l_type = F_UNLCK;
if (pidfile) {
rewind(pidfile);
ftruncate(fileno(pidfile), 0);
- fcntl(fileno(pidfile), F_SETLK, &lock);
fclose(pidfile);
pidfile = NULL;
}
{
if (daemon_process) {
info("stopping...");
+ pidfile_close();
}
- pidfile_close();
for (int i = -1; __madexit[i]; i--) {
(*__madexit[i])();
}
return EXIT_FAILURE;
}
+ if (pidfile_open(pidfile) < 0) {
+ crit("unable to write pidfile %s", pidfile);
+ return EXIT_FAILURE;
+ }
+
if (drop_privileges(RUNAS_USER, RUNAS_GROUP) < 0) {
crit("unable to drop privileges");
return EXIT_FAILURE;
config->port = port;
}
- if (common_setup(pidfile, true, NULL, NULL, daemonize) != EXIT_SUCCESS
- || start_listener(config->port) < 0) {
+ if (daemonize && daemon_detach() < 0) {
+ crit("unable to fork");
+ return EXIT_FAILURE;
+ }
+
+ pidfile_refresh();
+
+ if (start_listener(config->port) < 0) {
return EXIT_FAILURE;
} else {
return server_loop(query_starter, (delete_client_t)query_delete,