Add a threading framework
[apps/pfixtools.git] / main-postlicyd.c
index 6810bba..fe4a851 100644 (file)
  * Copyright © 2006-2007 Pierre Habouzit
  */
 
-#include <signal.h>
-#include <time.h>
 #include <getopt.h>
 
-#include "common.h"
+#include "epoll.h"
+#include "threads.h"
 
 /* administrivia {{{ */
 
@@ -62,47 +61,77 @@ module_exit(main_shutdown);
 
 /* }}} */
 
-void *job_run(void *_fd)
+void *job_run(int fd, void *data)
 {
-    int fd = (intptr_t)_fd;
-
     close(fd);
     return NULL;
 }
 
-static void main_loop(void)
+static int main_loop(void)
 {
+    int exitcode = EXIT_SUCCESS;
     int sock = -1;
 
     while (!sigint) {
         int fd = accept(sock, NULL, 0);
-        pthread_attr_t attr;
-        pthread_t dummy;
-
         if (fd < 0) {
             if (errno != EINTR || errno != EAGAIN)
                 UNIXERR("accept");
             continue;
         }
 
-        pthread_attr_init(&attr);
-        pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
-        pthread_create(&dummy, &attr, job_run, (void *)(intptr_t)fd);
-        pthread_attr_destroy(&attr);
+        thread_launch(job_run, fd, NULL);
+        threads_join();
     }
 
     close(sock);
+    return exitcode;
 }
 
-int main(void)
+int main(int argc, char *argv[])
 {
-    if (atexit(common_shutdown)) {
-        fputs("Cannot hook my atexit function, quitting !\n", stderr);
+    const char *pidfile = NULL;
+    FILE *f = NULL;
+    int res;
+
+    for (int c = 0; (c = getopt(argc, argv, "h" "p:")) >= 0; ) {
+        switch (c) {
+          case 'p':
+            pidfile = optarg;
+            break;
+          default:
+            //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 (daemon_detach() < 0) {
+        syslog(LOG_CRIT, "unable to fork");
         return EXIT_FAILURE;
     }
 
-    common_initialize();
-    main_loop();
+    if (f) {
+        rewind(f);
+        ftruncate(fileno(f), 0);
+        fprintf(f, "%d\n", getpid());
+        fflush(f);
+    }
+    res = main_loop();
+    if (f) {
+        rewind(f);
+        ftruncate(fileno(f), 0);
+        fclose(f);
+        f = NULL;
+    }
     syslog(LOG_INFO, "Stopping...");
-    return EXIT_SUCCESS;
+    return res;
 }