2 * lock.c -- cross-platform concurrency locking for fetchmail
4 * For license terms, see the file COPYING in this directory.
9 #if defined(STDC_HEADERS)
12 #if defined(HAVE_UNISTD_H)
17 #include "fetchmail.h"
20 static char *lockfile; /* name of lockfile */
21 static int lock_acquired; /* have we acquired a lock */
24 /* set up the global lockfile name */
26 /* set up to do lock protocol */
27 #define FETCHMAIL_PIDFILE "fetchmail.pid"
29 xalloca(lockfile, char *,
30 sizeof(PID_DIR) + sizeof(FETCHMAIL_PIDFILE));
31 sprintf(lockfile, "%s/%s", PID_DIR, FETCHMAIL_PIDFILE);
33 xalloca(lockfile, char *, strlen(fmhome) + sizeof(FETCHMAIL_PIDFILE) + 2);
34 strcpy(lockfile, fmhome);
35 strcat(lockfile, "/");
37 strcat(lockfile, ".");
38 strcat(lockfile, FETCHMAIL_PIDFILE);
40 #undef FETCHMAIL_PIDFILE
44 static void unlockit(int n, void *p)
46 static void unlockit(void)
48 /* must-do actions for exit (but we can't count on being able to do malloc) */
50 if (lockfile && lock_acquired)
54 void lock_dispose(void)
55 /* arrange for a lock to be removed on process exit */
61 on_exit(unlockit, (char *)NULL);
72 if ((lockfp = fopen(lockfile, "r")) != NULL )
74 bkgd = (fscanf(lockfp, "%d %d", &pid, &st) == 2);
76 if (kill(pid, 0) == -1) {
77 fprintf(stderr,_("fetchmail: removing stale lockfile\n"));
81 fclose(lockfp); /* not checking should be safe, file mode was "r" */
84 return(bkgd ? -pid : pid);
87 void lock_assert(void)
88 /* assert that we already posess a lock */
93 void lock_or_die(void)
94 /* get a lock on a given host or exit */
100 #define O_SYNC 0 /* use it if we have it */
104 if ((fd = open(lockfile, O_WRONLY|O_CREAT|O_EXCL|O_SYNC, 0666)) != -1)
106 sprintf(tmpbuf,"%d", getpid());
107 write(fd, tmpbuf, strlen(tmpbuf));
108 if (run.poll_interval)
110 sprintf(tmpbuf," %d", run.poll_interval);
111 write(fd, tmpbuf, strlen(tmpbuf));
113 close(fd); /* should be safe, fd was opened with O_SYNC */
114 lock_acquired = TRUE;
118 fprintf(stderr, _("fetchmail: lock creation failed.\n"));
124 void lock_release(void)
125 /* release a lock on a given host */
130 /* lock.c ends here */