]> git.ipfire.org Git - thirdparty/util-linux.git/blob - sys-utils/flock.c
flock: improve usage strings
[thirdparty/util-linux.git] / sys-utils / flock.c
1 /* Copyright 2003-2005 H. Peter Anvin - All Rights Reserved
2 *
3 * Permission is hereby granted, free of charge, to any person
4 * obtaining a copy of this software and associated documentation
5 * files (the "Software"), to deal in the Software without
6 * restriction, including without limitation the rights to use,
7 * copy, modify, merge, publish, distribute, sublicense, and/or
8 * sell copies of the Software, and to permit persons to whom
9 * the Software is furnished to do so, subject to the following
10 * conditions:
11 *
12 * The above copyright notice and this permission notice shall
13 * be included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
17 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22 * OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25 #include <ctype.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <getopt.h>
29 #include <paths.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <sysexits.h>
35 #include <sys/file.h>
36 #include <sys/stat.h>
37 #include <sys/time.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40 #include <unistd.h>
41
42 #include "c.h"
43 #include "nls.h"
44 #include "strutils.h"
45 #include "closestream.h"
46
47 static void __attribute__((__noreturn__)) usage(int ex)
48 {
49 fprintf(stderr, USAGE_HEADER);
50 fprintf(stderr,
51 _(" %1$s [options] <file|directory> <command> [command args]\n"
52 " %1$s [options] <file|directory> -c <command>\n"
53 " %1$s [options] <file descriptor number>\n"),
54 program_invocation_short_name);
55 fputs(USAGE_OPTIONS, stderr);
56 fputs(_( " -s --shared get a shared lock\n"), stderr);
57 fputs(_( " -x --exclusive get an exclusive lock (default)\n"), stderr);
58 fputs(_( " -u --unlock remove a lock\n"), stderr);
59 fputs(_( " -n --nonblock fail rather than wait\n"), stderr);
60 fputs(_( " -w --timeout <secs> wait for a limited amount of time\n"), stderr);
61 fputs(_( " -E --conflict-exit-code <number> exit code after conflict or timeout\n"), stderr);
62 fputs(_( " -o --close close file descriptor before running command\n"), stderr);
63 fputs(_( " -c --command <command> run a single command string through the shell\n"), stderr);
64 fprintf(stderr, USAGE_SEPARATOR);
65 fprintf(stderr, USAGE_HELP);
66 fprintf(stderr, USAGE_VERSION);
67 fprintf(stderr, USAGE_MAN_TAIL("flock(1)"));
68 exit(ex);
69 }
70
71 static sig_atomic_t timeout_expired = 0;
72
73 static void timeout_handler(int sig __attribute__((__unused__)))
74 {
75 timeout_expired = 1;
76 }
77
78 static void strtotimeval(const char *str, struct timeval *tv)
79 {
80 double user_input;
81
82 user_input = strtod_or_err(str, "bad number");
83 tv->tv_sec = (time_t) user_input;
84 tv->tv_usec = (long)((user_input - tv->tv_sec) * 1000000);
85 if ((tv->tv_sec + tv->tv_usec) == 0)
86 errx(EX_USAGE, _("timeout cannot be zero"));
87 }
88
89 static void setup_timer(struct itimerval *timer, struct itimerval *old_timer,
90 struct sigaction *sa, struct sigaction *old_sa)
91 {
92 memset(sa, 0, sizeof *sa);
93 sa->sa_handler = timeout_handler;
94 sa->sa_flags = SA_RESETHAND;
95 sigaction(SIGALRM, sa, old_sa);
96 setitimer(ITIMER_REAL, timer, old_timer);
97 }
98
99 static void cancel_timer(struct itimerval *old_timer, struct sigaction *old_sa)
100 {
101 setitimer(ITIMER_REAL, old_timer, NULL);
102 sigaction(SIGALRM, old_sa, NULL);
103 }
104
105 static int open_file(const char *filename, int *flags)
106 {
107
108 int fd;
109 int fl = *flags == 0 ? O_RDONLY : *flags;
110
111 errno = 0;
112 fl |= O_NOCTTY | O_CREAT;
113 fd = open(filename, fl, 0666);
114
115 /* Linux doesn't like O_CREAT on a directory, even though it
116 * should be a no-op; POSIX doesn't allow O_RDWR or O_WRONLY
117 */
118 if (fd < 0 && errno == EISDIR) {
119 fl = O_RDONLY | O_NOCTTY;
120 fd = open(filename, fl);
121 }
122 if (fd < 0) {
123 warn(_("cannot open lock file %s"), filename);
124 if (errno == ENOMEM || errno == EMFILE || errno == ENFILE)
125 exit(EX_OSERR);
126 if (errno == EROFS || errno == ENOSPC)
127 exit(EX_CANTCREAT);
128 exit(EX_NOINPUT);
129 }
130 *flags = fl;
131 return fd;
132 }
133
134 int main(int argc, char *argv[])
135 {
136 struct itimerval timeout, old_timer;
137 int have_timeout = 0;
138 int type = LOCK_EX;
139 int block = 0;
140 int open_flags = 0;
141 int fd = -1;
142 int opt, ix;
143 int do_close = 0;
144 int status;
145 /*
146 * The default exit code for lock conflict or timeout
147 * is specified in man flock.1
148 */
149 int conflict_exit_code = 1;
150 char **cmd_argv = NULL, *sh_c_argv[4];
151 const char *filename = NULL;
152 struct sigaction sa, old_sa;
153
154 static const struct option long_options[] = {
155 {"shared", no_argument, NULL, 's'},
156 {"exclusive", no_argument, NULL, 'x'},
157 {"unlock", no_argument, NULL, 'u'},
158 {"nonblocking", no_argument, NULL, 'n'},
159 {"nb", no_argument, NULL, 'n'},
160 {"timeout", required_argument, NULL, 'w'},
161 {"wait", required_argument, NULL, 'w'},
162 {"conflict-exit-code", required_argument, NULL, 'E'},
163 {"close", no_argument, NULL, 'o'},
164 {"help", no_argument, NULL, 'h'},
165 {"version", no_argument, NULL, 'V'},
166 {NULL, 0, NULL, 0}
167 };
168
169 setlocale(LC_ALL, "");
170 bindtextdomain(PACKAGE, LOCALEDIR);
171 textdomain(PACKAGE);
172 atexit(close_stdout);
173
174 if (argc < 2)
175 usage(EX_USAGE);
176
177 memset(&timeout, 0, sizeof timeout);
178
179 optopt = 0;
180 while ((opt =
181 getopt_long(argc, argv, "+sexnouw:E:hV?", long_options,
182 &ix)) != EOF) {
183 switch (opt) {
184 case 's':
185 type = LOCK_SH;
186 break;
187 case 'e':
188 case 'x':
189 type = LOCK_EX;
190 break;
191 case 'u':
192 type = LOCK_UN;
193 break;
194 case 'o':
195 do_close = 1;
196 break;
197 case 'n':
198 block = LOCK_NB;
199 break;
200 case 'w':
201 have_timeout = 1;
202 strtotimeval(optarg, &timeout.it_value);
203 break;
204 case 'E':
205 conflict_exit_code = strtos32_or_err(optarg,
206 _("invalid exit code"));
207 break;
208 case 'V':
209 printf("flock (%s)\n", PACKAGE_STRING);
210 exit(EX_OK);
211 default:
212 /* optopt will be set if this was an unrecognized
213 * option, i.e. *not* 'h' or '?
214 */
215 usage(optopt ? EX_USAGE : 0);
216 break;
217 }
218 }
219
220 if (argc > optind + 1) {
221 /* Run command */
222 if (!strcmp(argv[optind + 1], "-c") ||
223 !strcmp(argv[optind + 1], "--command")) {
224 if (argc != optind + 3)
225 errx(EX_USAGE,
226 _("%s requires exactly one command argument"),
227 argv[optind + 1]);
228 cmd_argv = sh_c_argv;
229 cmd_argv[0] = getenv("SHELL");
230 if (!cmd_argv[0] || !*cmd_argv[0])
231 cmd_argv[0] = _PATH_BSHELL;
232 cmd_argv[1] = "-c";
233 cmd_argv[2] = argv[optind + 2];
234 cmd_argv[3] = 0;
235 } else {
236 cmd_argv = &argv[optind + 1];
237 }
238
239 filename = argv[optind];
240 fd = open_file(filename, &open_flags);
241
242 } else if (optind < argc) {
243 /* Use provided file descriptor */
244 fd = (int)strtol_or_err(argv[optind], "bad number");
245 } else {
246 /* Bad options */
247 errx(EX_USAGE, _("requires file descriptor, file or directory"));
248 }
249
250 if (have_timeout) {
251 if (timeout.it_value.tv_sec == 0 &&
252 timeout.it_value.tv_usec == 0) {
253 /* -w 0 is equivalent to -n; this has to be
254 * special-cased because setting an itimer to zero
255 * means disabled!
256 */
257 have_timeout = 0;
258 block = LOCK_NB;
259 } else
260 setup_timer(&timeout, &old_timer, &sa, &old_sa);
261 }
262
263 while (flock(fd, type | block)) {
264 switch (errno) {
265 case EWOULDBLOCK:
266 /* -n option set and failed to lock. */
267 exit(conflict_exit_code);
268 case EINTR:
269 /* Signal received */
270 if (timeout_expired)
271 /* -w option set and failed to lock. */
272 exit(conflict_exit_code);
273 /* otherwise try again */
274 continue;
275 case EIO:
276 /* Probably NFSv4 where flock() is emulated by fcntl().
277 * Let's try to reopen in read-write mode.
278 */
279 if (!(open_flags & O_RDWR) &&
280 type != LOCK_SH &&
281 access(filename, R_OK | W_OK) == 0) {
282
283 close(fd);
284 open_flags = O_RDWR;
285 fd = open_file(filename, &open_flags);
286
287 if (open_flags & O_RDWR)
288 break;
289 }
290 /* go through */
291 default:
292 /* Other errors */
293 if (filename)
294 warn("%s", filename);
295 else
296 warn("%d", fd);
297 exit((errno == ENOLCK
298 || errno == ENOMEM) ? EX_OSERR : EX_DATAERR);
299 }
300 }
301
302 if (have_timeout)
303 cancel_timer(&old_timer, &old_sa);
304
305 status = EX_OK;
306
307 if (cmd_argv) {
308 pid_t w, f;
309 /* Clear any inherited settings */
310 signal(SIGCHLD, SIG_DFL);
311 f = fork();
312
313 if (f < 0) {
314 err(EX_OSERR, _("fork failed"));
315 } else if (f == 0) {
316 if (do_close)
317 close(fd);
318 execvp(cmd_argv[0], cmd_argv);
319 /* execvp() failed */
320 warn("%s", cmd_argv[0]);
321 _exit((errno == ENOMEM) ? EX_OSERR : EX_UNAVAILABLE);
322 } else {
323 do {
324 w = waitpid(f, &status, 0);
325 if (w == -1 && errno != EINTR)
326 break;
327 } while (w != f);
328
329 if (w == -1) {
330 status = EXIT_FAILURE;
331 warn(_("waitpid failed"));
332 } else if (WIFEXITED(status))
333 status = WEXITSTATUS(status);
334 else if (WIFSIGNALED(status))
335 status = WTERMSIG(status) + 128;
336 else
337 /* WTF? */
338 status = EX_OSERR;
339 }
340 }
341
342 return status;
343 }