1 /* ----------------------------------------------------------------------- *
3 * Copyright 2003-2005 H. Peter Anvin - All Rights Reserved
5 * Permission is hereby granted, free of charge, to any person
6 * obtaining a copy of this software and associated documentation
7 * files (the "Software"), to deal in the Software without
8 * restriction, including without limitation the rights to use,
9 * copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Software, and to permit persons to whom
11 * the Software is furnished to do so, subject to the following
14 * The above copyright notice and this permission notice shall
15 * be included in all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
19 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
21 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
22 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24 * OTHER DEALINGS IN THE SOFTWARE.
26 * ----------------------------------------------------------------------- */
38 #include <sys/types.h>
44 #define PACKAGE_STRING "util-linux-ng 2.18"
47 static const struct option long_options[] = {
48 { "shared", 0, NULL, 's' },
49 { "exclusive", 0, NULL, 'x' },
50 { "unlock", 0, NULL, 'u' },
51 { "nonblocking", 0, NULL, 'n' },
52 { "nb", 0, NULL, 'n' },
53 { "timeout", 1, NULL, 'w' },
54 { "wait", 1, NULL, 'w' },
55 { "close", 0, NULL, 'o' },
56 { "help", 0, NULL, 'h' },
57 { "version", 0, NULL, 'V' },
63 static void usage(int ex)
65 fputs("flock (" PACKAGE_STRING ")\n", stderr);
67 _("Usage: %1$s [-sxun][-w #] fd#\n"
68 " %1$s [-sxon][-w #] file [-c] command...\n"
69 " %1$s [-sxon][-w #] directory [-c] command...\n"
70 " -s --shared Get a shared lock\n"
71 " -x --exclusive Get an exclusive lock\n"
72 " -u --unlock Remove a lock\n"
73 " -n --nonblock Fail rather than wait\n"
74 " -w --timeout Wait for a limited amount of time\n"
75 " -o --close Close file descriptor before running command\n"
76 " -c --command Run a single command string through the shell\n"
77 " -h --help Display this text\n"
78 " -V --version Display version\n"),
84 static sig_atomic_t timeout_expired = 0;
86 static void timeout_handler(int sig)
94 static char * strtotimeval(const char *str, struct timeval *tv)
97 long fs; /* Fractional seconds */
100 tv->tv_sec = strtol(str, &s, 10);
106 for ( i = 0 ; i < 6 ; i++ ) {
117 while ( isdigit(*s) )
125 int main(int argc, char *argv[])
127 struct itimerval timeout, old_timer;
128 int have_timeout = 0;
137 char **cmd_argv = NULL, *sh_c_argv[4];
138 const char *filename = NULL;
139 struct sigaction sa, old_sa;
146 memset(&timeout, 0, sizeof timeout);
149 while ( (opt = getopt_long(argc, argv, "+sexnouw:hV?", long_options, &ix)) != EOF ) {
169 eon = strtotimeval(optarg, &timeout.it_value);
174 printf("flock (%s)\n", PACKAGE_STRING);
177 /* optopt will be set if this was an unrecognized option, i.e. *not* 'h' or '?' */
178 usage(optopt ? EX_USAGE : 0);
183 if ( argc > optind+1 ) {
186 if ( !strcmp(argv[optind+1], "-c") ||
187 !strcmp(argv[optind+1], "--command") ) {
189 if ( argc != optind+3 ) {
190 fprintf(stderr, _("%s: %s requires exactly one command argument\n"),
191 program, argv[optind+1]);
195 cmd_argv = sh_c_argv;
197 cmd_argv[0] = getenv("SHELL");
198 if ( !cmd_argv[0] || !*cmd_argv[0] )
199 cmd_argv[0] = _PATH_BSHELL;
202 cmd_argv[2] = argv[optind+2];
205 cmd_argv = &argv[optind+1];
208 filename = argv[optind];
209 fd = open(filename, O_RDONLY|O_NOCTTY|O_CREAT, 0666);
210 /* Linux doesn't like O_CREAT on a directory, even though it should be a
212 if (fd < 0 && errno == EISDIR)
213 fd = open(filename, O_RDONLY|O_NOCTTY);
217 fprintf(stderr, _("%s: cannot open lock file %s: %s\n"),
218 program, argv[optind], strerror(err));
219 exit((err == ENOMEM||err == EMFILE||err == ENFILE) ? EX_OSERR :
220 (err == EROFS||err == ENOSPC) ? EX_CANTCREAT :
224 } else if (optind < argc) {
225 /* Use provided file descriptor */
227 fd = (int)strtol(argv[optind], &eon, 10);
228 if ( *eon || !argv[optind] ) {
229 fprintf(stderr, _("%s: bad number: %s\n"), program, argv[optind]);
236 fprintf(stderr, _("%s: requires file descriptor, file or directory\n"),
242 if ( have_timeout ) {
243 if ( timeout.it_value.tv_sec == 0 &&
244 timeout.it_value.tv_usec == 0 ) {
245 /* -w 0 is equivalent to -n; this has to be special-cased
246 because setting an itimer to zero means disabled! */
251 memset(&sa, 0, sizeof sa);
253 sa.sa_handler = timeout_handler;
254 sa.sa_flags = SA_RESETHAND;
255 sigaction(SIGALRM, &sa, &old_sa);
257 setitimer(ITIMER_REAL, &timeout, &old_timer);
261 while ( flock(fd, type|block) ) {
262 switch( (err = errno) ) {
263 case EWOULDBLOCK: /* -n option set and failed to lock */
265 case EINTR: /* Signal received */
266 if ( timeout_expired )
267 exit(1); /* -w option set and failed to lock */
268 continue; /* otherwise try again */
269 default: /* Other errors */
271 fprintf(stderr, "%s: %s: %s\n", program, filename, strerror(err));
273 fprintf(stderr, "%s: %d: %s\n", program, fd, strerror(err));
274 exit((err == ENOLCK||err == ENOMEM) ? EX_OSERR : EX_DATAERR);
278 if ( have_timeout ) {
279 setitimer(ITIMER_REAL, &old_timer, NULL); /* Cancel itimer */
280 sigaction(SIGALRM, &old_sa, NULL); /* Cancel signal handler */
288 /* Clear any inherited settings */
289 signal(SIGCHLD, SIG_DFL);
294 fprintf(stderr, _("%s: fork failed: %s\n"), program, strerror(err));
296 } else if ( f == 0 ) {
300 execvp(cmd_argv[0], cmd_argv);
301 /* execvp() failed */
302 fprintf(stderr, "%s: %s: %s\n", program, cmd_argv[0], strerror(err));
303 _exit((err == ENOMEM) ? EX_OSERR: EX_UNAVAILABLE);
306 w = waitpid(f, &status, 0);
307 if (w == -1 && errno != EINTR)
313 status = EXIT_FAILURE;
314 fprintf(stderr, "%s: waitpid failed: %s\n", program, strerror(err));
315 } else if ( WIFEXITED(status) )
316 status = WEXITSTATUS(status);
317 else if ( WIFSIGNALED(status) )
318 status = WTERMSIG(status) + 128;
320 status = EX_OSERR; /* WTF? */