flock.c 8.7 KB

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