comparison common/linuxlockfile.c @ 782:20ca94680003

Implemented detection of running instance on linux using a lock file.
author Sascha Wilde <wilde@intevation.de>
date Mon, 14 Jul 2014 12:46:47 +0200
parents
children a974b61a5cce
comparison
equal deleted inserted replaced
773:2c69298b4188 782:20ca94680003
1 #ifndef WIN32
2
3 #include <fcntl.h>
4 #include <stdio.h>
5 #include <sys/types.h>
6 #include <unistd.h>
7
8 #include "logging.h"
9
10 int
11 open_lockfile(char *path)
12 {
13 int fd;
14 char pidstr[20];
15 size_t pidstrlen;
16 struct flock lk;
17 fd = open(path, O_RDWR | O_CREAT, 0600);
18 if (fd != -1)
19 {
20 /* Get an exclusive lock on the whole file. */
21 lk.l_type = F_WRLCK;
22 lk.l_whence = SEEK_SET;
23 lk.l_start = 0;
24 lk.l_len = 0;
25 if (fcntl(fd, F_SETLK, &lk) != -1)
26 {
27 /* FIXME: For extra security we should check if there is
28 already a pid in the file. If so we should check in
29 /proc/$PID if there is still a process of the same name
30 as ours running... */
31 ftruncate(fd, 0);
32 pidstrlen = (size_t)snprintf(pidstr, sizeof(pidstr), "%d", getpid());
33 write(fd, pidstr, pidstrlen);
34 }
35 else
36 {
37 /* Lock can not be acquired. Bail out... */
38 close(fd);
39 DEBUGPRINTF("Could not get an exclusive lock on %s.\n", path);
40 return -1;
41 }
42 }
43 else
44 {
45 DEBUGPRINTF("Failed to open lock file: %s.\n", path);
46 }
47 return fd;
48 }
49
50 void
51 close_lockfile(int fd)
52 {
53 struct flock lk;
54
55 /* Delete the PID from file. */
56 /* We do this instead of trying to unlink the file. */
57 ftruncate(fd, 0);
58
59 /* Remove lock from the file. */
60 lk.l_type = F_UNLCK;
61 lk.l_whence = SEEK_SET;
62 lk.l_start = 0;
63 lk.l_len = 0;
64 if (fcntl(fd, F_SETLK, &lk) == -1)
65 {
66 /* Lock can not be removed?!? WTF? */
67 DEBUGPRINTF("Could not remove lock from pid file. STRANGE!\n");
68 }
69 close(fd);
70 }
71
72 #endif /* Not WIN32 */

http://wald.intevation.org/projects/trustbridge/