/[imapfilter]/imapfilter/lock.c
ViewVC logotype

Contents of /imapfilter/lock.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.5.2.2 - (show annotations)
Sun Aug 25 10:27:49 2002 UTC (21 years, 7 months ago) by lefcha
Branch: release-0_8-patches
Changes since 1.5.2.1: +15 -9 lines
File MIME type: text/plain
Remove stale lockfile.

1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <limits.h>
4 #include <string.h>
5 #include <errno.h>
6 #include <sys/types.h>
7 #include <signal.h>
8
9 #include "imapfilter.h"
10
11
12 extern char *home;
13
14 static char *lockfile = NULL; /* Lock file to stop new imapfilter
15 processes. */
16
17
18 /*
19 * Create lockfile with the PID of imapfilter as its contents.
20 */
21 void lockfile_create(void)
22 {
23 FILE *fd;
24
25 create_file(lockfile, S_IRUSR | S_IWUSR);
26
27 fd = fopen(lockfile, "w");
28 if (!fd)
29 fatal(ERROR_FILE_OPEN, "imapfilter: opening lockfile; %s\n",
30 strerror(errno));
31 fprintf(fd, "%s\n", ultostr(getpid(), 10));
32 fclose(fd);
33 }
34
35
36 /*
37 * Die if another instance of imapfilter is running.
38 */
39 void lockfile_check(void)
40 {
41 pid_t n;
42 char lockf[PATH_MAX];
43
44 snprintf(lockf, PATH_MAX, "%s/%s", home, ".imapfilter/lock");
45 lockfile = xstrdup(lockf);
46
47 if ((n = lockfile_pid())) {
48 errno = 0;
49 kill(n, 0);
50 if (errno == ESRCH) { /* Process does not exist. */
51 fprintf(stderr, "imapfilter: removing stale lockfile\n");
52 lockfile_remove();
53 } else {
54 fprintf(stderr,
55 "imapfilter: another imapfilter"
56 "is running with pid %d\n", n);
57 exit(ERROR_LOCKFILE);
58 }
59 }
60 }
61
62
63 /*
64 * Check if lockfile exists and if so, return the PID of the other
65 * imapfilter running.
66 */
67 pid_t lockfile_pid(void)
68 {
69 char line[LINE_MAX];
70 FILE *fd;
71 pid_t n = 0;
72
73 if (exists_file(lockfile)) {
74 fd = fopen(lockfile, "r");
75 if (!fd)
76 fatal(ERROR_FILE_OPEN, "imapfilter: opening lockfile; %s\n",
77 strerror(errno));
78 if (fgets(line, LINE_MAX - 1, fd)) {
79 errno = 0;
80 n = strtoul(line, NULL, 10);
81 if (errno)
82 n = 0;
83 }
84 fclose(fd);
85 }
86 return n;
87 }
88
89
90 /*
91 * Unlink the lockfile.
92 */
93 int lockfile_remove(void)
94 {
95 if (!lockfile)
96 return 0;
97
98 if (unlink(lockfile) && errno != ENOENT) {
99 error("imapfilter: removing lockfile; %s\n", strerror(errno));
100 return ERROR_FILE_OPEN;
101 }
102 return 0;
103 }
104
105
106 /*
107 * Kill the other instance of imapfilter (if one is running).
108 */
109 void kill_imapfilter(void)
110 {
111 pid_t n;
112
113 n = lockfile_pid();
114
115 if (n > 0) {
116 if (kill(n, SIGTERM))
117 fprintf(stderr, "imapfilter: killing process with pid %d; %s\n",
118 n, strerror(errno));
119 lockfile_remove();
120 exit(0);
121 } else {
122 fprintf(stderr, "imapfilter: no other imapfilter is running\n");
123 exit(ERROR_UNDEFINED);
124 }
125 }

webmaster@linux.gr
ViewVC Help
Powered by ViewVC 1.1.26