1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
/*
CTDB mutex fcntl lock file helper
Copyright (C) Martin Schwenke 2015
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include "replace.h"
#include "system/filesys.h"
#include "system/network.h"
/* protocol.h is just needed for ctdb_sock_addr, which is used in system.h */
#include "protocol/protocol.h"
#include "common/system.h"
static char *progname = NULL;
static char fcntl_lock(const char *file, int *outfd)
{
int fd;
struct flock lock;
fd = open(file, O_RDWR|O_CREAT, 0600);
if (fd == -1) {
fprintf(stderr, "%s: Unable to open %s - (%s)\n",
progname, file, strerror(errno));
return '3';
}
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 1;
lock.l_pid = 0;
if (fcntl(fd, F_SETLK, &lock) != 0) {
int saved_errno = errno;
close(fd);
fd = -1;
if (saved_errno == EACCES ||
saved_errno == EAGAIN) {
/* Lock contention, fail silently */
return '1';
}
/* Log an error for any other failure */
fprintf(stderr,
"%s: Failed to get lock on '%s' - (%s)\n",
progname, file, strerror(saved_errno));
return '3';
}
*outfd = fd;
return '0';
}
int main(int argc, char *argv[])
{
char result;
int ppid;
const char *file = NULL;
int fd = -1;
progname = argv[0];
if (argc != 2) {
fprintf(stderr, "Usage: %s <file>\n", progname);
exit(1);
}
ppid = getppid();
file = argv[1];
result = fcntl_lock(file, &fd);
sys_write(STDOUT_FILENO, &result, 1);
ctdb_wait_for_process_to_exit(ppid);
if (fd != -1) {
close(fd);
}
return 0;
}
|