+ if (flags & FLAG_DAEMON) {
+ FILE *pidfile = NULL;
+
+ if (flags & FLAG_PID_FILE) {
+ int fd;
+
+ fd = open(PID_FILE, O_CREAT | O_EXCL | O_WRONLY, 0644);
+ if (fd == -1) {
+ if (errno == EEXIST) {
+ pid_t old_pid;
+ pidfile = fopen(PID_FILE, "r");
+ if (!pidfile) {
+ perror("PID file " PID_FILE " already exists, already running?");
+ exit(EXIT_FAILURE);
+ }
+
+ if (fscanf(pidfile, "%u", &old_pid) != 1) {
+ fclose(pidfile);
+ fprintf(stderr, "Can't read old PID from " PID_FILE ", already running?\n");
+ exit(EXIT_FAILURE);
+ }
+
+ fclose(pidfile);
+
+ fprintf(stderr, "Already running with PID %u according to " PID_FILE "!\n", old_pid);
+ exit(EXIT_FAILURE);
+ }
+ perror("Can't create PID file " PID_FILE);
+ exit(EXIT_FAILURE);
+ }
+
+ pidfile = fdopen(fd, "w");
+ if (!pidfile) {
+ perror("Can't reopen PID file fd");
+ exit(EXIT_FAILURE);
+ }
+
+ memset(&sact, 0, sizeof(sact));
+ sact.sa_handler = sigterm_handler;
+
+ if (sigaction(SIGTERM, &sact, NULL) == -1) {
+ perror("sigaction(SIGTERM)");
+ exit(EXIT_FAILURE);
+ }
+ }
+