]> mj.ucw.cz Git - libucw.git/blobdiff - ucw/daemon.c
Doc: Release dates
[libucw.git] / ucw / daemon.c
index 7606f8075d7322e55f4b6e21c80d0c8cddeee997..268bda461bcae397b2ee07a091253c694dcf48fc 100644 (file)
@@ -18,6 +18,8 @@
 #include <pwd.h>
 #include <grp.h>
 #include <errno.h>
+#include <sys/types.h>
+#include <sys/stat.h>
 #include <sys/file.h>
 
 static void
@@ -82,6 +84,9 @@ daemon_init(struct daemon_params *dp)
 {
   daemon_resolve_ugid(dp);
 
+  if (dp->flags & DAEMON_FLAG_SIMULATE)
+    return;
+
   if (dp->pid_file)
     {
       // Check that PID file path is absolute
@@ -115,6 +120,12 @@ daemon_init(struct daemon_params *dp)
 void
 daemon_run(struct daemon_params *dp, void (*body)(struct daemon_params *dp))
 {
+  if (dp->flags & DAEMON_FLAG_SIMULATE)
+    {
+      body(dp);
+      return;
+    }
+
   // Switch GID and UID
   if (dp->want_setgid && setresgid(dp->run_as_gid, dp->run_as_gid, dp->run_as_gid) < 0)
     die("Cannot set GID to %d: %m", (int) dp->run_as_gid);
@@ -168,6 +179,9 @@ daemon_run(struct daemon_params *dp, void (*body)(struct daemon_params *dp))
 void
 daemon_exit(struct daemon_params *dp)
 {
+  if (dp->flags & DAEMON_FLAG_SIMULATE)
+    return;
+
   if (dp->pid_file)
     {
       if (unlink(dp->pid_file) < 0)
@@ -178,12 +192,43 @@ daemon_exit(struct daemon_params *dp)
 
 #ifdef TEST
 
+#include <signal.h>
+
+static volatile sig_atomic_t terminate;
+
+static void term_handler(int sig UNUSED)
+{
+  msg(L_INFO | L_SIGHANDLER, "SIGTERM received, terminating in a while");
+  terminate = 1;
+}
+
+static void hup_handler(int sig UNUSED)
+{
+  msg(L_INFO | L_SIGHANDLER, "SIGHUP received");
+}
+
 static void body(struct daemon_params *dp)
 {
   log_fork();
   msg(L_INFO, "Daemon is running");
   msg(L_INFO, "uid=%d/%d gid=%d/%d", (int) getuid(), (int) geteuid(), (int) getgid(), (int) getegid());
-  sleep(60);
+
+  struct sigaction sa_term = { .sa_handler = term_handler };
+  struct sigaction sa_hup = { .sa_handler = hup_handler };
+  if (sigaction(SIGTERM, &sa_term, NULL) < 0 ||
+      sigaction(SIGHUP, &sa_hup, NULL) < 0)
+    ASSERT(0);
+
+  while (!terminate)
+    {
+      if (!sleep(60))
+       {
+         msg(L_INFO, "Timeout elapsed, terminating in a while");
+         break;
+       }
+    }
+
+  sleep(2);
   msg(L_INFO, "Daemon is shutting down");
   daemon_exit(dp);
 }