s3-printing: fix migrate printer code (bug 8618)
[Samba.git] / ctdb / server / ctdb_mutex_fcntl_helper.c
blob87358beb234d12db997bb44e421b673c98ced808
1 /*
2 CTDB mutex fcntl lock file helper
4 Copyright (C) Martin Schwenke 2015
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, see <http://www.gnu.org/licenses/>.
20 #include "replace.h"
21 #include "system/filesys.h"
22 #include "system/network.h"
24 /* protocol.h is just needed for ctdb_sock_addr, which is used in system.h */
25 #include "protocol/protocol.h"
26 #include "common/system.h"
28 static char *progname = NULL;
30 static char fcntl_lock(const char *file, int *outfd)
32 int fd;
33 struct flock lock;
35 fd = open(file, O_RDWR|O_CREAT, 0600);
36 if (fd == -1) {
37 fprintf(stderr, "%s: Unable to open %s - (%s)\n",
38 progname, file, strerror(errno));
39 return '3';
42 lock.l_type = F_WRLCK;
43 lock.l_whence = SEEK_SET;
44 lock.l_start = 0;
45 lock.l_len = 1;
46 lock.l_pid = 0;
48 if (fcntl(fd, F_SETLK, &lock) != 0) {
49 int saved_errno = errno;
50 close(fd);
51 fd = -1;
52 if (saved_errno == EACCES ||
53 saved_errno == EAGAIN) {
54 /* Lock contention, fail silently */
55 return '1';
58 /* Log an error for any other failure */
59 fprintf(stderr,
60 "%s: Failed to get lock on '%s' - (%s)\n",
61 progname, file, strerror(saved_errno));
62 return '3';
65 *outfd = fd;
67 return '0';
70 int main(int argc, char *argv[])
72 char result;
73 int ppid;
74 const char *file = NULL;
75 int fd = -1;
77 progname = argv[0];
79 if (argc != 2) {
80 fprintf(stderr, "Usage: %s <file>\n", progname);
81 exit(1);
84 ppid = getppid();
86 if (ppid == 1) {
87 /* The original parent is gone and the process has
88 * been reparented to init. This can happen if the
89 * helper is started just as the parent is killed
90 * during shutdown. The error message doesn't need to
91 * be stellar, since there won't be anything around to
92 * capture and log it...
94 fprintf(stderr, "%s: PPID == 1\n", progname);
95 exit(1);
98 file = argv[1];
100 result = fcntl_lock(file, &fd);
101 sys_write(STDOUT_FILENO, &result, 1);
103 ctdb_wait_for_process_to_exit(ppid);
105 if (fd != -1) {
106 close(fd);
109 return 0;