Upload Tizen:Base source
[framework/base/util-linux-ng.git] / sys-utils / flock.c
1 /* ----------------------------------------------------------------------- *
2  *
3  *   Copyright 2003-2005 H. Peter Anvin - All Rights Reserved
4  *
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
12  *   conditions:
13  *
14  *   The above copyright notice and this permission notice shall
15  *   be included in all copies or substantial portions of the Software.
16  *
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.
25  *
26  * ----------------------------------------------------------------------- */
27
28 #include <errno.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <unistd.h>
32 #include <getopt.h>
33 #include <signal.h>
34 #include <ctype.h>
35 #include <string.h>
36 #include <paths.h>
37 #include <sysexits.h>
38 #include <sys/types.h>
39 #include <sys/file.h>
40 #include <sys/time.h>
41 #include <sys/wait.h>
42
43 #include "nls.h"
44
45 static const struct option long_options[] = {
46   { "shared",       0, NULL, 's' },
47   { "exclusive",    0, NULL, 'x' },
48   { "unlock",       0, NULL, 'u' },
49   { "nonblocking",  0, NULL, 'n' },
50   { "nb",           0, NULL, 'n' },
51   { "timeout",      1, NULL, 'w' },
52   { "wait",         1, NULL, 'w' },
53   { "close",        0, NULL, 'o' },
54   { "help",         0, NULL, 'h' },
55   { "version",      0, NULL, 'V' },
56   { 0, 0, 0, 0 }
57 };
58
59 const char *program;
60
61 static void usage(int ex)
62 {
63   fputs("flock (" PACKAGE_STRING ")\n", stderr);
64   fprintf(stderr,
65         _("Usage: %1$s [-sxun][-w #] fd#\n"
66           "       %1$s [-sxon][-w #] file [-c] command...\n"
67           "       %1$s [-sxon][-w #] directory [-c] command...\n"
68           "  -s  --shared     Get a shared lock\n"
69           "  -x  --exclusive  Get an exclusive lock\n"
70           "  -u  --unlock     Remove a lock\n"
71           "  -n  --nonblock   Fail rather than wait\n"
72           "  -w  --timeout    Wait for a limited amount of time\n"
73           "  -o  --close      Close file descriptor before running command\n"
74           "  -c  --command    Run a single command string through the shell\n"
75           "  -h  --help       Display this text\n"
76           "  -V  --version    Display version\n"),
77           program);
78   exit(ex);
79 }
80
81
82 static sig_atomic_t timeout_expired = 0;
83
84 static void timeout_handler(int sig)
85 {
86   (void)sig;
87
88   timeout_expired = 1;
89 }
90
91
92 static char * strtotimeval(const char *str, struct timeval *tv)
93 {
94   char *s;
95   long fs;                      /* Fractional seconds */
96   int i;
97
98   tv->tv_sec = strtol(str, &s, 10);
99   fs = 0;
100
101   if ( *s == '.' ) {
102     s++;
103
104     for ( i = 0 ; i < 6 ; i++ ) {
105       if ( !isdigit(*s) )
106         break;
107
108       fs *= 10;
109       fs += *s++ - '0';
110     }
111
112     for ( ; i < 6; i++ )
113       fs *= 10;
114
115     while ( isdigit(*s) )
116       s++;
117   }
118
119   tv->tv_usec = fs;
120   return s;
121 }
122
123 int main(int argc, char *argv[])
124 {
125   struct itimerval timeout, old_timer;
126   int have_timeout = 0;
127   int type = LOCK_EX;
128   int block = 0;
129   int fd = -1;
130   int opt, ix;
131   int do_close = 0;
132   int err;
133   int status;
134   char *eon;
135   char **cmd_argv = NULL, *sh_c_argv[4];
136   const char *filename = NULL;
137   struct sigaction sa, old_sa;
138
139   setlocale(LC_ALL, "");
140   bindtextdomain(PACKAGE, LOCALEDIR);
141   textdomain(PACKAGE);
142
143   program = argv[0];
144
145   if ( argc < 2 )
146     usage(EX_USAGE);
147
148   memset(&timeout, 0, sizeof timeout);
149
150   optopt = 0;
151   while ( (opt = getopt_long(argc, argv, "+sexnouw:hV?", long_options, &ix)) != EOF ) {
152     switch(opt) {
153     case 's':
154       type = LOCK_SH;
155       break;
156     case 'e':
157     case 'x':
158       type = LOCK_EX;
159       break;
160     case 'u':
161       type = LOCK_UN;
162       break;
163     case 'o':
164       do_close = 1;
165       break;
166     case 'n':
167       block = LOCK_NB;
168       break;
169     case 'w':
170       have_timeout = 1;
171       eon = strtotimeval(optarg, &timeout.it_value);
172       if ( *eon )
173         usage(EX_USAGE);
174       break;
175     case 'V':
176       printf("flock (%s)\n", PACKAGE_STRING);
177       exit(0);
178     default:
179       /* optopt will be set if this was an unrecognized option, i.e. *not* 'h' or '?' */
180       usage(optopt ? EX_USAGE : 0);
181       break;
182     }
183   }
184
185   if ( argc > optind+1 ) {
186     /* Run command */
187
188     if ( !strcmp(argv[optind+1], "-c") ||
189          !strcmp(argv[optind+1], "--command") ) {
190
191       if ( argc != optind+3 ) {
192         fprintf(stderr, _("%s: %s requires exactly one command argument\n"),
193                 program, argv[optind+1]);
194         exit(EX_USAGE);
195       }
196
197       cmd_argv = sh_c_argv;
198
199       cmd_argv[0] = getenv("SHELL");
200       if ( !cmd_argv[0] || !*cmd_argv[0] )
201         cmd_argv[0] = _PATH_BSHELL;
202
203       cmd_argv[1] = "-c";
204       cmd_argv[2] = argv[optind+2];
205       cmd_argv[3] = 0;
206     } else {
207       cmd_argv = &argv[optind+1];
208     }
209
210     filename = argv[optind];
211     fd = open(filename, O_RDONLY|O_NOCTTY|O_CREAT, 0666);
212     /* Linux doesn't like O_CREAT on a directory, even though it should be a
213        no-op */
214     if (fd < 0 && errno == EISDIR)
215         fd = open(filename, O_RDONLY|O_NOCTTY);
216
217     if ( fd < 0 ) {
218       err = errno;
219       fprintf(stderr, _("%s: cannot open lock file %s: %s\n"),
220               program, argv[optind], strerror(err));
221       exit((err == ENOMEM||err == EMFILE||err == ENFILE) ? EX_OSERR :
222            (err == EROFS||err == ENOSPC) ? EX_CANTCREAT :
223            EX_NOINPUT);
224     }
225
226   } else if (optind < argc) {
227     /* Use provided file descriptor */
228
229     fd = (int)strtol(argv[optind], &eon, 10);
230     if ( *eon || !argv[optind] ) {
231       fprintf(stderr, _("%s: bad number: %s\n"), program, argv[optind]);
232       exit(EX_USAGE);
233     }
234
235   } else {
236     /* Bad options */
237
238     fprintf(stderr, _("%s: requires file descriptor, file or directory\n"),
239                 program);
240     exit(EX_USAGE);
241   }
242
243
244   if ( have_timeout ) {
245     if ( timeout.it_value.tv_sec == 0 &&
246          timeout.it_value.tv_usec == 0 ) {
247       /* -w 0 is equivalent to -n; this has to be special-cased
248          because setting an itimer to zero means disabled! */
249
250       have_timeout = 0;
251       block = LOCK_NB;
252     } else {
253       memset(&sa, 0, sizeof sa);
254
255       sa.sa_handler = timeout_handler;
256       sa.sa_flags   = SA_ONESHOT;
257       sigaction(SIGALRM, &sa, &old_sa);
258
259       setitimer(ITIMER_REAL, &timeout, &old_timer);
260     }
261   }
262
263   while ( flock(fd, type|block) ) {
264     switch( (err = errno) ) {
265     case EWOULDBLOCK:           /* -n option set and failed to lock */
266       exit(1);
267     case EINTR:                 /* Signal received */
268       if ( timeout_expired )
269         exit(1);                /* -w option set and failed to lock */
270       continue;                 /* otherwise try again */
271     default:                    /* Other errors */
272       if ( filename )
273         fprintf(stderr, "%s: %s: %s\n", program, filename, strerror(err));
274       else
275         fprintf(stderr, "%s: %d: %s\n", program, fd, strerror(err));
276       exit((err == ENOLCK||err == ENOMEM) ? EX_OSERR : EX_DATAERR);
277     }
278   }
279
280   if ( have_timeout ) {
281     setitimer(ITIMER_REAL, &old_timer, NULL); /* Cancel itimer */
282     sigaction(SIGALRM, &old_sa, NULL); /* Cancel signal handler */
283   }
284
285   status = 0;
286
287   if ( cmd_argv ) {
288     pid_t w, f;
289
290     f = fork();
291
292     if ( f < 0 ) {
293       err = errno;
294       fprintf(stderr, _("%s: fork failed: %s\n"), program, strerror(err));
295       exit(EX_OSERR);
296     } else if ( f == 0 ) {
297       if ( do_close )
298         close(fd);
299       err = errno;
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);
304     } else {
305       do {
306         w = waitpid(f, &status, 0);
307       } while ( w != f );
308
309       if ( WIFEXITED(status) )
310         status = WEXITSTATUS(status);
311       else if ( WIFSIGNALED(status) )
312         status = WTERMSIG(status) + 128;
313       else
314         status = EX_OSERR;      /* WTF? */
315     }
316   }
317
318   return status;
319 }
320