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 if (info
->si_code
== SI_TIMER
)
88 static int open_file(const char *filename
, int *flags
)
92 int fl
= *flags
== 0 ? O_RDONLY
: *flags
;
95 fl
|= O_NOCTTY
| O_CREAT
;
96 fd
= open(filename
, fl
, 0666);
98 /* Linux doesn't like O_CREAT on a directory, even though it
99 * should be a no-op; POSIX doesn't allow O_RDWR or O_WRONLY
101 if (fd
< 0 && errno
== EISDIR
) {
102 fl
= O_RDONLY
| O_NOCTTY
;
103 fd
= open(filename
, fl
);
106 warn(_("cannot open lock file %s"), filename
);
107 if (errno
== ENOMEM
|| errno
== EMFILE
|| errno
== ENFILE
)
109 if (errno
== EROFS
|| errno
== ENOSPC
)
117 static void __attribute__((__noreturn__
)) run_program(char **cmd_argv
)
119 execvp(cmd_argv
[0], cmd_argv
);
121 warn(_("failed to execute %s"), cmd_argv
[0]);
122 _exit((errno
== ENOMEM
) ? EX_OSERR
: EX_UNAVAILABLE
);
125 int main(int argc
, char *argv
[])
128 struct itimerval timeout
;
129 int have_timeout
= 0;
139 struct timeval time_start
, time_done
;
141 * The default exit code for lock conflict or timeout
142 * is specified in man flock.1
144 int conflict_exit_code
= 1;
145 char **cmd_argv
= NULL
, *sh_c_argv
[4];
146 const char *filename
= NULL
;
148 OPT_VERBOSE
= CHAR_MAX
+ 1
150 static const struct option long_options
[] = {
151 {"shared", no_argument
, NULL
, 's'},
152 {"exclusive", no_argument
, NULL
, 'x'},
153 {"unlock", no_argument
, NULL
, 'u'},
154 {"nonblocking", no_argument
, NULL
, 'n'},
155 {"nb", no_argument
, NULL
, 'n'},
156 {"timeout", required_argument
, NULL
, 'w'},
157 {"wait", required_argument
, NULL
, 'w'},
158 {"conflict-exit-code", required_argument
, NULL
, 'E'},
159 {"close", no_argument
, NULL
, 'o'},
160 {"no-fork", no_argument
, NULL
, 'F'},
161 {"verbose", no_argument
, NULL
, OPT_VERBOSE
},
162 {"help", no_argument
, NULL
, 'h'},
163 {"version", no_argument
, NULL
, 'V'},
167 setlocale(LC_ALL
, "");
168 bindtextdomain(PACKAGE
, LOCALEDIR
);
170 atexit(close_stdout
);
172 strutils_set_exitcode(EX_USAGE
);
175 warnx(_("not enough arguments"));
176 errtryhelp(EX_USAGE
);
179 memset(&timeout
, 0, sizeof timeout
);
183 getopt_long(argc
, argv
, "+sexnoFuw:E:hV?", long_options
,
207 strtotimeval_or_err(optarg
, &timeout
.it_value
,
208 _("invalid timeout value"));
211 conflict_exit_code
= strtos32_or_err(optarg
,
212 _("invalid exit code"));
218 printf(UTIL_LINUX_VERSION
);
223 errtryhelp(EX_USAGE
);
227 if (no_fork
&& do_close
)
229 _("the --no-fork and --close options are incompatible"));
231 if (argc
> optind
+ 1) {
233 if (!strcmp(argv
[optind
+ 1], "-c") ||
234 !strcmp(argv
[optind
+ 1], "--command")) {
235 if (argc
!= optind
+ 3)
237 _("%s requires exactly one command argument"),
239 cmd_argv
= sh_c_argv
;
240 cmd_argv
[0] = getenv("SHELL");
241 if (!cmd_argv
[0] || !*cmd_argv
[0])
242 cmd_argv
[0] = _PATH_BSHELL
;
244 cmd_argv
[2] = argv
[optind
+ 2];
247 cmd_argv
= &argv
[optind
+ 1];
250 filename
= argv
[optind
];
251 fd
= open_file(filename
, &open_flags
);
253 } else if (optind
< argc
) {
254 /* Use provided file descriptor */
255 fd
= strtos32_or_err(argv
[optind
], _("bad file descriptor"));
258 errx(EX_USAGE
, _("requires file descriptor, file or directory"));
262 if (timeout
.it_value
.tv_sec
== 0 &&
263 timeout
.it_value
.tv_usec
== 0) {
264 /* -w 0 is equivalent to -n; this has to be
265 * special-cased because setting an itimer to zero
271 if (setup_timer(&t_id
, &timeout
, &timeout_handler
))
272 err(EX_OSERR
, _("cannot set up timer"));
276 gettime_monotonic(&time_start
);
277 while (flock(fd
, type
| block
)) {
280 /* -n option set and failed to lock. */
282 warnx(_("failed to get lock"));
283 exit(conflict_exit_code
);
285 /* Signal received */
286 if (timeout_expired
) {
287 /* -w option set and failed to lock. */
289 warnx(_("timeout while waiting to get lock"));
290 exit(conflict_exit_code
);
292 /* otherwise try again */
295 case EBADF
: /* since Linux 3.4 (commit 55725513) */
296 /* Probably NFSv4 where flock() is emulated by fcntl().
297 * Let's try to reopen in read-write mode.
299 if (!(open_flags
& O_RDWR
) &&
302 access(filename
, R_OK
| W_OK
) == 0) {
306 fd
= open_file(filename
, &open_flags
);
308 if (open_flags
& O_RDWR
)
315 warn("%s", filename
);
318 exit((errno
== ENOLCK
319 || errno
== ENOMEM
) ? EX_OSERR
: EX_DATAERR
);
326 struct timeval delta
;
328 gettime_monotonic(&time_done
);
329 timersub(&time_done
, &time_start
, &delta
);
330 printf(_("%s: getting lock took %ld.%06ld seconds\n"),
331 program_invocation_short_name
, delta
.tv_sec
,
338 /* Clear any inherited settings */
339 signal(SIGCHLD
, SIG_DFL
);
341 printf(_("%s: executing %s\n"), program_invocation_short_name
, cmd_argv
[0]);
346 err(EX_OSERR
, _("fork failed"));
352 run_program(cmd_argv
);
357 w
= waitpid(f
, &status
, 0);
358 if (w
== -1 && errno
!= EINTR
)
363 status
= EXIT_FAILURE
;
364 warn(_("waitpid failed"));
365 } else if (WIFEXITED(status
))
366 status
= WEXITSTATUS(status
);
367 else if (WIFSIGNALED(status
))
368 status
= WTERMSIG(status
) + 128;
375 /* no-fork execution */
376 run_program(cmd_argv
);