remove stale pidfile if no such process found
authorMartin Willi <martin@strongswan.org>
Tue, 9 Jun 2009 12:56:31 +0000 (14:56 +0200)
committerMartin Willi <martin@strongswan.org>
Tue, 9 Jun 2009 12:56:31 +0000 (14:56 +0200)
src/charon/daemon.c

index 8b30588..3df2fbb 100644 (file)
@@ -612,6 +612,48 @@ private_daemon_t *daemon_create(void)
 }
 
 /**
+ * Check/create PID file, return TRUE if already running 
+ */
+static bool check_pidfile()
+{
+       struct stat stb;
+       FILE *file;
+       
+       if (stat(PID_FILE, &stb) == 0)
+       {
+               file = fopen(PID_FILE, "r");
+               if (file)
+               {
+                       char buf[64];
+                       pid_t pid = 0;
+                       
+                       memset(buf, 0, sizeof(buf));
+                       if (fread(buf, 1, sizeof(buf), file))
+                       {
+                               pid = atoi(buf);
+                       }
+                       fclose(file);
+                       if (pid && kill(pid, 0) == 0)
+                       {       /* such a process is running */
+                               return TRUE;
+                       }
+               }
+               DBG1(DBG_DMN, "removing pidfile '"PID_FILE"', process not running");
+               unlink(PID_FILE);
+       }
+       
+       /* create new pidfile */
+       file = fopen(PID_FILE, "w");
+       if (file)
+       {
+               fprintf(file, "%d\n", getpid());
+               ignore_result(fchown(fileno(file), charon->uid, charon->gid));
+               fclose(file);
+       }
+       return FALSE;
+}
+
+/**
  * print command line usage and exit
  */
 static void usage(const char *msg)
@@ -639,10 +681,7 @@ static void usage(const char *msg)
 int main(int argc, char *argv[])
 {
        bool use_syslog = FALSE;
-
        private_daemon_t *private_charon;
-       FILE *pid_file;
-       struct stat stb;
        level_t levels[DBG_MAX];
        int group;
        
@@ -723,21 +762,13 @@ int main(int argc, char *argv[])
                destroy(private_charon);
                exit(-1);
        }
-
-       /* check/setup PID file */
-       if (stat(PID_FILE, &stb) == 0)
+       
+       if (check_pidfile())
        {
                DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
                destroy(private_charon);
                exit(-1);
        }
-       pid_file = fopen(PID_FILE, "w");
-       if (pid_file)
-       {
-               fprintf(pid_file, "%d\n", getpid());
-               ignore_result(fchown(fileno(pid_file), charon->uid, charon->gid));
-               fclose(pid_file);
-       }
        
        /* drop the capabilities we won't need */
        drop_capabilities(private_charon);