1 /* Copyright 2003-2005 H. Peter Anvin - All Rights Reserved
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
12 * The above copyright notice and this permission notice shall
13 * be included in all copies or substantial portions of the Software.
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.
38 #include <sys/types.h>
45 #include "closestream.h"
46 #include "monotonic.h"
49 static void __attribute__((__noreturn__
)) usage(void)
51 fputs(USAGE_HEADER
, stdout
);
53 _(" %1$s [options] <file>|<directory> <command> [<argument>...]\n"
54 " %1$s [options] <file>|<directory> -c <command>\n"
55 " %1$s [options] <file descriptor number>\n"),
56 program_invocation_short_name
);
58 fputs(USAGE_SEPARATOR
, stdout
);
59 fputs(_("Manage file locks from shell scripts.\n"), stdout
);
61 fputs(USAGE_OPTIONS
, stdout
);
62 fputs(_( " -s, --shared get a shared lock\n"), stdout
);
63 fputs(_( " -x, --exclusive get an exclusive lock (default)\n"), stdout
);
64 fputs(_( " -u, --unlock remove a lock\n"), stdout
);
65 fputs(_( " -n, --nonblock fail rather than wait\n"), stdout
);
66 fputs(_( " -w, --timeout <secs> wait for a limited amount of time\n"), stdout
);
67 fputs(_( " -E, --conflict-exit-code <number> exit code after conflict or timeout\n"), stdout
);
68 fputs(_( " -o, --close close file descriptor before running command\n"), stdout
);
69 fputs(_( " -c, --command <command> run a single command string through the shell\n"), stdout
);
70 fputs(_( " -F, --no-fork execute command without forking\n"), stdout
);
71 fputs(_( " --verbose increase verbosity\n"), stdout
);
72 fputs(USAGE_SEPARATOR
, stdout
);
73 printf(USAGE_HELP_OPTIONS(26));
74 printf(USAGE_MAN_TAIL("flock(1)"));
78 static sig_atomic_t timeout_expired
= 0;
80 static void timeout_handler(int sig
__attribute__((__unused__
)),
82 void *context
__attribute__((__unused__
)))
84 #ifdef HAVE_TIMER_CREATE
85 if (info
->si_code
== SI_TIMER
)
90 static int open_file(const char *filename
, int *flags
)
94 int fl
= *flags
== 0 ? O_RDONLY
: *flags
;
97 fl
|= O_NOCTTY
| O_CREAT
;
98 fd
= open(filename
, fl
, 0666);
100 /* Linux doesn't like O_CREAT on a directory, even though it
101 * should be a no-op; POSIX doesn't allow O_RDWR or O_WRONLY
103 if (fd
< 0 && errno
== EISDIR
) {
104 fl
= O_RDONLY
| O_NOCTTY
;
105 fd
= open(filename
, fl
);
108 warn(_("cannot open lock file %s"), filename
);
109 if (errno
== ENOMEM
|| errno
== EMFILE
|| errno
== ENFILE
)
111 if (errno
== EROFS
|| errno
== ENOSPC
)
119 static void __attribute__((__noreturn__
)) run_program(char **cmd_argv
)
121 execvp(cmd_argv
[0], cmd_argv
);
123 warn(_("failed to execute %s"), cmd_argv
[0]);
124 _exit((errno
== ENOMEM
) ? EX_OSERR
: EX_UNAVAILABLE
);
127 int main(int argc
, char *argv
[])
129 struct ul_timer timer
;
130 struct itimerval timeout
;
131 int have_timeout
= 0;
141 struct timeval time_start
, time_done
;
143 * The default exit code for lock conflict or timeout
144 * is specified in man flock.1
146 int conflict_exit_code
= 1;
147 char **cmd_argv
= NULL
, *sh_c_argv
[4];
148 const char *filename
= NULL
;
150 OPT_VERBOSE
= CHAR_MAX
+ 1
152 static const struct option long_options
[] = {
153 {"shared", no_argument
, NULL
, 's'},
154 {"exclusive", no_argument
, NULL
, 'x'},
155 {"unlock", no_argument
, NULL
, 'u'},
156 {"nonblocking", no_argument
, NULL
, 'n'},
157 {"nb", no_argument
, NULL
, 'n'},
158 {"timeout", required_argument
, NULL
, 'w'},
159 {"wait", required_argument
, NULL
, 'w'},
160 {"conflict-exit-code", required_argument
, NULL
, 'E'},
161 {"close", no_argument
, NULL
, 'o'},
162 {"no-fork", no_argument
, NULL
, 'F'},
163 {"verbose", no_argument
, NULL
, OPT_VERBOSE
},
164 {"help", no_argument
, NULL
, 'h'},
165 {"version", no_argument
, NULL
, 'V'},
169 setlocale(LC_ALL
, "");
170 bindtextdomain(PACKAGE
, LOCALEDIR
);
172 atexit(close_stdout
);
174 strutils_set_exitcode(EX_USAGE
);
177 warnx(_("not enough arguments"));
178 errtryhelp(EX_USAGE
);
181 memset(&timeout
, 0, sizeof timeout
);
185 getopt_long(argc
, argv
, "+sexnoFuw:E:hV?", long_options
,
209 strtotimeval_or_err(optarg
, &timeout
.it_value
,
210 _("invalid timeout value"));
213 conflict_exit_code
= strtos32_or_err(optarg
,
214 _("invalid exit code"));
220 printf(UTIL_LINUX_VERSION
);
225 errtryhelp(EX_USAGE
);
229 if (no_fork
&& do_close
)
231 _("the --no-fork and --close options are incompatible"));
233 if (argc
> optind
+ 1) {
235 if (!strcmp(argv
[optind
+ 1], "-c") ||
236 !strcmp(argv
[optind
+ 1], "--command")) {
237 if (argc
!= optind
+ 3)
239 _("%s requires exactly one command argument"),
241 cmd_argv
= sh_c_argv
;
242 cmd_argv
[0] = getenv("SHELL");
243 if (!cmd_argv
[0] || !*cmd_argv
[0])
244 cmd_argv
[0] = _PATH_BSHELL
;
246 cmd_argv
[2] = argv
[optind
+ 2];
249 cmd_argv
= &argv
[optind
+ 1];
252 filename
= argv
[optind
];
253 fd
= open_file(filename
, &open_flags
);
255 } else if (optind
< argc
) {
256 /* Use provided file descriptor */
257 fd
= strtos32_or_err(argv
[optind
], _("bad file descriptor"));
260 errx(EX_USAGE
, _("requires file descriptor, file or directory"));
264 if (timeout
.it_value
.tv_sec
== 0 &&
265 timeout
.it_value
.tv_usec
== 0) {
266 /* -w 0 is equivalent to -n; this has to be
267 * special-cased because setting an itimer to zero
273 if (setup_timer(&timer
, &timeout
, &timeout_handler
))
274 err(EX_OSERR
, _("cannot set up timer"));
278 gettime_monotonic(&time_start
);
279 while (flock(fd
, type
| block
)) {
282 /* -n option set and failed to lock. */
284 warnx(_("failed to get lock"));
285 exit(conflict_exit_code
);
287 /* Signal received */
288 if (timeout_expired
) {
289 /* -w option set and failed to lock. */
291 warnx(_("timeout while waiting to get lock"));
292 exit(conflict_exit_code
);
294 /* otherwise try again */
297 case EBADF
: /* since Linux 3.4 (commit 55725513) */
298 /* Probably NFSv4 where flock() is emulated by fcntl().
299 * Let's try to reopen in read-write mode.
301 if (!(open_flags
& O_RDWR
) &&
304 access(filename
, R_OK
| W_OK
) == 0) {
308 fd
= open_file(filename
, &open_flags
);
310 if (open_flags
& O_RDWR
)
317 warn("%s", filename
);
320 exit((errno
== ENOLCK
321 || errno
== ENOMEM
) ? EX_OSERR
: EX_DATAERR
);
326 cancel_timer(&timer
);
328 struct timeval delta
;
330 gettime_monotonic(&time_done
);
331 timersub(&time_done
, &time_start
, &delta
);
332 printf(_("%s: getting lock took %ld.%06ld seconds\n"),
333 program_invocation_short_name
, delta
.tv_sec
,
340 /* Clear any inherited settings */
341 signal(SIGCHLD
, SIG_DFL
);
343 printf(_("%s: executing %s\n"), program_invocation_short_name
, cmd_argv
[0]);
348 err(EX_OSERR
, _("fork failed"));
354 run_program(cmd_argv
);
359 w
= waitpid(f
, &status
, 0);
360 if (w
== -1 && errno
!= EINTR
)
365 status
= EXIT_FAILURE
;
366 warn(_("waitpid failed"));
367 } else if (WIFEXITED(status
))
368 status
= WEXITSTATUS(status
);
369 else if (WIFSIGNALED(status
))
370 status
= WTERMSIG(status
) + 128;
377 /* no-fork execution */
378 run_program(cmd_argv
);