Simple concurrency lock to prevent multiple citservers running at the same time
[citadel.git] / citadel / server_main.c
index 443fdd3bb4db68a9633072b910f8a098320ba352..061273a6336c034c2357039bf40ad3db4802a952 100644 (file)
@@ -14,6 +14,7 @@
 #include <stdio.h>
 #include <sys/types.h>
 #include <grp.h>
+#include <sys/file.h>
 #include <libcitadel.h>
 
 #include "citserver.h"
@@ -34,6 +35,42 @@ const char *CitadelServiceTCP="citadel-TCP";
 
 void go_threading(void);
 
+
+
+/*
+ * Create or remove a lock file, so we only have one Citadel Server running at a time.
+ */
+void ctdl_lockfile(int yo) {
+       static char lockfilename[SIZ];
+       static FILE *fp;
+
+
+       if (yo) {
+               syslog(LOG_DEBUG, "Creating lockfile");
+               snprintf(lockfilename, sizeof lockfilename, "%s/citadel.lock", ctdl_run_dir);
+               fp = fopen(lockfilename, "w");
+               if (!fp) {
+                       syslog(LOG_ERR, "Cannot open or create %s", lockfilename);
+                       exit(CTDLEXIT_DB);
+               }
+               if (flock(fileno(fp), (LOCK_EX|LOCK_NB)) != 0) {
+                       syslog(LOG_ERR, "Cannot lock %s , is another citserver running?", lockfilename);
+                       exit(CTDLEXIT_DB);
+               }
+               return;
+       }
+
+       syslog(LOG_DEBUG, "Removing lockfile");
+       unlink(lockfilename);
+       flock(fileno(fp), LOCK_UN);
+       fclose(fp);
+}
+
+
+
+
+
+
 /*
  * Here's where it all begins.
  */
@@ -195,9 +232,8 @@ int main(int argc, char **argv)
        /* Tell 'em who's in da house */
        syslog(LOG_NOTICE, " ");
        syslog(LOG_NOTICE, " ");
-       syslog(LOG_NOTICE,
-               "*** Citadel server engine v%d.%02d (build %s) ***",
-               (REV_LEVEL/100), (REV_LEVEL%100), svn_revision());
+       syslog(LOG_NOTICE, "*** Citadel server engine ***\n");
+       syslog(LOG_NOTICE, "Version %d (build %s) ***", REV_LEVEL, svn_revision());
        syslog(LOG_NOTICE, "Copyright (C) 1987-2016 by the Citadel development team.");
        syslog(LOG_NOTICE, "This program is distributed under the terms of the GNU "
                                        "General Public License.");
@@ -233,6 +269,8 @@ int main(int argc, char **argv)
 
 #endif
 
+       ctdl_lockfile(1);
+
        /* Initialize... */
        init_sysdep();
 
@@ -363,6 +401,7 @@ int main(int argc, char **argv)
 
        go_threading();
        
-       master_cleanup(exit_signal);
-       return(0);
+       int exit_code = master_cleanup(exit_signal);
+       ctdl_lockfile(0);
+       return(exit_code);
 }