flock.c 8.2 KB

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