Have a generic pidfile API.
[apps/pfixtools.git] / main-postlicyd.c
index 01eb9e6..ecf60f0 100644 (file)
 
 #include <getopt.h>
 
-#include "common.h"
 #include "epoll.h"
+#include "threads.h"
+
+#define DAEMON_NAME             "postlicyd"
 
 /* administrivia {{{ */
 
@@ -59,14 +61,20 @@ static void main_shutdown(void)
 module_init(main_initialize);
 module_exit(main_shutdown);
 
+void usage(void)
+{
+    fputs("usage: "DAEMON_NAME" [options] config\n"
+          "\n"
+          "Options:\n"
+          "    -p <pidfile> file to write our pid to\n"
+         , stderr);
+}
+
 /* }}} */
 
-void *job_run(void *_fd)
+void *job_run(int fd, void *data)
 {
-    int fd = (intptr_t)_fd;
-
     close(fd);
-    pthread_detach(pthread_self());
     return NULL;
 }
 
@@ -77,15 +85,14 @@ static int main_loop(void)
 
     while (!sigint) {
         int fd = accept(sock, NULL, 0);
-        pthread_t dummy;
-
         if (fd < 0) {
             if (errno != EINTR || errno != EAGAIN)
                 UNIXERR("accept");
             continue;
         }
 
-        pthread_create(&dummy, NULL, job_run, (void *)(intptr_t)fd);
+        thread_launch(job_run, fd, NULL);
+        threads_join();
     }
 
     close(sock);
@@ -95,7 +102,6 @@ static int main_loop(void)
 int main(int argc, char *argv[])
 {
     const char *pidfile = NULL;
-    FILE *f = NULL;
     int res;
 
     for (int c = 0; (c = getopt(argc, argv, "h" "p:")) >= 0; ) {
@@ -104,18 +110,19 @@ int main(int argc, char *argv[])
             pidfile = optarg;
             break;
           default:
-            //usage();
+            usage();
             return EXIT_FAILURE;
         }
     }
 
-    if (pidfile) {
-        f = fopen(pidfile, "w");
-        if (!f) {
-            syslog(LOG_CRIT, "unable to write pidfile %s", pidfile);
-        }
-        fprintf(f, "%d\n", getpid());
-        fflush(f);
+    if (argc - optind != 1) {
+        usage();
+        return EXIT_FAILURE;
+    }
+
+    if (pidfile_open(pidfile) < 0) {
+        syslog(LOG_CRIT, "unable to write pidfile %s", pidfile);
+        return EXIT_FAILURE;
     }
 
     if (daemon_detach() < 0) {
@@ -123,19 +130,8 @@ int main(int argc, char *argv[])
         return EXIT_FAILURE;
     }
 
-    if (f) {
-        rewind(f);
-        ftruncate(fileno(f), 0);
-        fprintf(f, "%d\n", getpid());
-        fflush(f);
-    }
+    pidfile_refresh();
     res = main_loop();
-    if (f) {
-        rewind(f);
-        ftruncate(fileno(f), 0);
-        fclose(f);
-        f = NULL;
-    }
     syslog(LOG_INFO, "Stopping...");
     return res;
 }