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

Contents of /imapfilter/lock.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.5.2.1 - (show annotations)
Mon Jul 29 00:57:03 2002 UTC (21 years, 8 months ago) by lefcha
Branch: release-0_8-patches
Changes since 1.5: +2 -1 lines
File MIME type: text/plain
Bug fix with lockfile_remove() called twice and warning about non existent file.

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
43 if ((n = lockfile_pid())) {
44 fprintf(stderr,
45 "imapfilter: another imapfilter is running with pid %d\n", n);
46 exit(ERROR_LOCKFILE);
47 }
48 }
49
50
51 /*
52 * Check if lockfile exists and if so, return the PID of the other
53 * imapfilter running.
54 */
55 pid_t lockfile_pid(void)
56 {
57 char lockf[PATH_MAX];
58 char line[LINE_MAX];
59 FILE *fd;
60 pid_t n = 0;
61
62 snprintf(lockf, PATH_MAX, "%s/%s", home, ".imapfilter/lock");
63 lockfile = xstrdup(lockf);
64
65 if (exists_file(lockfile)) {
66 fd = fopen(lockfile, "r");
67 if (!fd)
68 fatal(ERROR_FILE_OPEN, "imapfilter: opening lockfile; %s\n",
69 strerror(errno));
70 if (fgets(line, LINE_MAX - 1, fd)) {
71 errno = 0;
72 n = strtoul(line, NULL, 10);
73 if (errno)
74 n = 0;
75 }
76 fclose(fd);
77 }
78 return n;
79 }
80
81
82 /*
83 * Unlink the lockfile.
84 */
85 int lockfile_remove(void)
86 {
87 if (!lockfile)
88 return 0;
89
90 if (unlink(lockfile) && errno != ENOENT) {
91 error("imapfilter: removing lockfile; %s\n", strerror(errno));
92 return ERROR_FILE_OPEN;
93 }
94 xfree(lockfile);
95
96 return 0;
97 }
98
99
100 /*
101 * Kill the other instance of imapfilter (if one is running).
102 */
103 void kill_imapfilter(void)
104 {
105 pid_t n;
106
107 n = lockfile_pid();
108
109 if (n > 0) {
110 if (kill(n, SIGTERM))
111 fprintf(stderr, "imapfilter: killing process with pid %d; %s\n",
112 n, strerror(errno));
113 lockfile_remove();
114 exit(0);
115 } else {
116 fprintf(stderr, "imapfilter: no other imapfilter is running\n");
117 exit(ERROR_UNDEFINED);
118 }
119 }

webmaster@linux.gr
ViewVC Help
Powered by ViewVC 1.1.26