]> Pileus Git - ~andy/fetchmail/blobdiff - lock.c
Attempt merging from 6.3.24.
[~andy/fetchmail] / lock.c
diff --git a/lock.c b/lock.c
index e56fe344359ad8dc031b76ca1719e124150d6fe1..2d656df65289fcf3ae829ac3d5306cb192fd3d03 100644 (file)
--- a/lock.c
+++ b/lock.c
@@ -6,21 +6,15 @@
 #include "config.h"
 
 #include <stdio.h>
-#ifdef HAVE_STRING_H
 #include <string.h> /* strcat() */
-#endif
-#if defined(STDC_HEADERS)
 #include <stdlib.h>
-#endif
-#if defined(HAVE_UNISTD_H)
 #include <unistd.h>
-#endif
 #include <errno.h>
 #include <fcntl.h>
 #include <signal.h>
 
 #include "fetchmail.h"
-#include "i18n.h"
+#include "gettext.h"
 #include "lock.h"
 
 static char *lockfile;         /** name of lockfile */
@@ -66,20 +60,19 @@ static void unlockit(void)
 void fm_lock_dispose(void)
 /* arrange for a lock to be removed on process exit */
 {
-#ifdef HAVE_ATEXIT
     atexit(unlockit);
-#endif
 }
 
 int fm_lock_state(void)
 {
-    int                pid, st;
+    long       pid;
+    int                st;
     FILE       *lockfp;
     int                bkgd = FALSE;
 
     if ((lockfp = fopen(lockfile, "r")) != NULL)
     {
-       int args = fscanf(lockfp, "%d %d", &pid, &st);
+       int args = fscanf(lockfp, "%ld %d", &pid, &st);
        bkgd = (args == 2);
 
        if (ferror(lockfp)) {
@@ -91,12 +84,27 @@ int fm_lock_state(void)
        fclose(lockfp); /* not checking should be safe, file mode was "r" */
 
        if (args == EOF || args == 0 || kill(pid, 0) == -1) {
+           /* ^ could not read PID  || process does not exist */
+           /* => lockfile is stale, unlink it */
            pid = 0;
-
            fprintf(stderr,GT_("fetchmail: removing stale lockfile\n"));
            if (unlink(lockfile)) {
               if (errno != ENOENT) {
                   perror(lockfile);
+                  /* we complain but we don't exit; it might be
+                   * writable for us, but in a directory we cannot
+                   * write to. This means we can write the new PID to
+                   * the file. Truncate to be safe in case the PID is
+                   * recycled by another process later.
+                   * \bug we should use fcntl() style locks or
+                   * something else instead in a future release. */
+                  if (truncate(lockfile, (off_t)0)) {
+                      /* but if we cannot truncate the file either,
+                       * assume that we cannot write to it later,
+                       * complain and quit. */
+                      perror(lockfile);
+                      exit(PS_EXCLUDE);
+                  }
               }
            }
        }