2 * lock.c -- cross-platform concurrency locking for fetchmail
4 * For license terms, see the file COPYING in this directory.
10 #include <string.h> /* strcat() */
12 #if defined(STDC_HEADERS)
15 #if defined(HAVE_UNISTD_H)
22 #include "fetchmail.h"
25 static char *lockfile; /* name of lockfile */
26 static int lock_acquired; /* have we acquired a lock */
29 /* set up the global lockfile name */
31 /* set up to do lock protocol */
32 #define FETCHMAIL_PIDFILE "fetchmail.pid"
33 if (getuid() == ROOT_UID) {
34 lockfile = (char *)xmalloc(
35 sizeof(PID_DIR) + sizeof(FETCHMAIL_PIDFILE) + 1);
36 strcpy(lockfile, PID_DIR);
37 strcat(lockfile, "/");
38 strcat(lockfile, FETCHMAIL_PIDFILE);
40 lockfile = (char *)xmalloc(strlen(fmhome)+sizeof(FETCHMAIL_PIDFILE)+2);
41 strcpy(lockfile, fmhome);
42 strcat(lockfile, "/");
44 strcat(lockfile, ".");
45 strcat(lockfile, FETCHMAIL_PIDFILE);
47 #undef FETCHMAIL_PIDFILE
51 static void unlockit(int n, void *p)
53 static void unlockit(void)
55 /* must-do actions for exit (but we can't count on being able to do malloc) */
57 if (lockfile && lock_acquired)
61 void lock_dispose(void)
62 /* arrange for a lock to be removed on process exit */
68 on_exit(unlockit, (char *)NULL);
78 if ((lockfp = fopen(lockfile, "r")) != NULL)
80 int args = fscanf(lockfp, "%d %d", &pid, &st);
84 fprintf(stderr, GT_("fetchmail: error reading lockfile \"%s\": %s\n"),
85 lockfile, strerror(errno));
87 if (args == 0 || kill(pid, 0) == -1) {
88 fprintf(stderr,GT_("fetchmail: removing stale lockfile\n"));
93 fclose(lockfp); /* not checking should be safe, file mode was "r" */
97 fprintf(stderr, GT_("fetchmail: error opening lockfile \"%s\": %s\n"),
98 lockfile, strerror(errno));
101 return(bkgd ? -pid : pid);
104 void lock_assert(void)
105 /* assert that we already posess a lock */
107 lock_acquired = TRUE;
110 void lock_or_die(void)
111 /* get a lock on a given host or exit */
116 if (!lock_acquired) {
119 if ((fd = open(lockfile, O_WRONLY|O_CREAT|O_EXCL, 0666)) != -1) {
120 snprintf(tmpbuf, sizeof(tmpbuf), "%ld\n", (long)getpid());
121 if (write(fd, tmpbuf, strlen(tmpbuf)) < strlen(tmpbuf)) e = 1;
122 if (run.poll_interval)
124 snprintf(tmpbuf, sizeof(tmpbuf), "%d\n", run.poll_interval);
125 if (write(fd, tmpbuf, strlen(tmpbuf)) < strlen(tmpbuf)) e = 1;
127 if (fsync(fd)) e = 1;
128 if (close(fd)) e = 1;
131 lock_acquired = TRUE;
134 fprintf(stderr, GT_("fetchmail: lock creation failed.\n"));
140 void lock_release(void)
141 /* release a lock on a given host */
145 /* lock.c ends here */