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"
47 static void __attribute__((__noreturn__
)) usage(int ex
)
49 fprintf(stderr
, USAGE_HEADER
);
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)"));
71 static sig_atomic_t timeout_expired
= 0;
73 static void timeout_handler(int sig
__attribute__((__unused__
)))
78 static void strtotimeval(const char *str
, struct timeval
*tv
)
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"));
89 static void setup_timer(struct itimerval
*timer
, struct itimerval
*old_timer
,
90 struct sigaction
*sa
, struct sigaction
*old_sa
)
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
);
99 static void cancel_timer(struct itimerval
*old_timer
, struct sigaction
*old_sa
)
101 setitimer(ITIMER_REAL
, old_timer
, NULL
);
102 sigaction(SIGALRM
, old_sa
, NULL
);
105 static int open_file(const char *filename
, int *flags
)
109 int fl
= *flags
== 0 ? O_RDONLY
: *flags
;
112 fl
|= O_NOCTTY
| O_CREAT
;
113 fd
= open(filename
, fl
, 0666);
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
118 if (fd
< 0 && errno
== EISDIR
) {
119 fl
= O_RDONLY
| O_NOCTTY
;
120 fd
= open(filename
, fl
);
123 warn(_("cannot open lock file %s"), filename
);
124 if (errno
== ENOMEM
|| errno
== EMFILE
|| errno
== ENFILE
)
126 if (errno
== EROFS
|| errno
== ENOSPC
)
134 int main(int argc
, char *argv
[])
136 struct itimerval timeout
, old_timer
;
137 int have_timeout
= 0;
146 * The default exit code for lock conflict or timeout
147 * is specified in man flock.1
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
;
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'},
169 setlocale(LC_ALL
, "");
170 bindtextdomain(PACKAGE
, LOCALEDIR
);
172 atexit(close_stdout
);
177 memset(&timeout
, 0, sizeof timeout
);
181 getopt_long(argc
, argv
, "+sexnouw:E:hV?", long_options
,
202 strtotimeval(optarg
, &timeout
.it_value
);
205 conflict_exit_code
= strtos32_or_err(optarg
,
206 _("invalid exit code"));
209 printf("flock (%s)\n", PACKAGE_STRING
);
212 /* optopt will be set if this was an unrecognized
213 * option, i.e. *not* 'h' or '?
215 usage(optopt
? EX_USAGE
: 0);
220 if (argc
> optind
+ 1) {
222 if (!strcmp(argv
[optind
+ 1], "-c") ||
223 !strcmp(argv
[optind
+ 1], "--command")) {
224 if (argc
!= optind
+ 3)
226 _("%s requires exactly one command argument"),
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
;
233 cmd_argv
[2] = argv
[optind
+ 2];
236 cmd_argv
= &argv
[optind
+ 1];
239 filename
= argv
[optind
];
240 fd
= open_file(filename
, &open_flags
);
242 } else if (optind
< argc
) {
243 /* Use provided file descriptor */
244 fd
= (int)strtol_or_err(argv
[optind
], "bad number");
247 errx(EX_USAGE
, _("requires file descriptor, file or directory"));
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
260 setup_timer(&timeout
, &old_timer
, &sa
, &old_sa
);
263 while (flock(fd
, type
| block
)) {
266 /* -n option set and failed to lock. */
267 exit(conflict_exit_code
);
269 /* Signal received */
271 /* -w option set and failed to lock. */
272 exit(conflict_exit_code
);
273 /* otherwise try again */
276 /* Probably NFSv4 where flock() is emulated by fcntl().
277 * Let's try to reopen in read-write mode.
279 if (!(open_flags
& O_RDWR
) &&
281 access(filename
, R_OK
| W_OK
) == 0) {
285 fd
= open_file(filename
, &open_flags
);
287 if (open_flags
& O_RDWR
)
294 warn("%s", filename
);
297 exit((errno
== ENOLCK
298 || errno
== ENOMEM
) ? EX_OSERR
: EX_DATAERR
);
303 cancel_timer(&old_timer
, &old_sa
);
309 /* Clear any inherited settings */
310 signal(SIGCHLD
, SIG_DFL
);
314 err(EX_OSERR
, _("fork failed"));
318 execvp(cmd_argv
[0], cmd_argv
);
319 /* execvp() failed */
320 warn("%s", cmd_argv
[0]);
321 _exit((errno
== ENOMEM
) ? EX_OSERR
: EX_UNAVAILABLE
);
324 w
= waitpid(f
, &status
, 0);
325 if (w
== -1 && errno
!= EINTR
)
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;