flock.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * Copyright (C) 2010 Timo Teras <timo.teras@iki.fi>
  3. *
  4. * This is free software, licensed under the GNU General Public License v2.
  5. */
  6. //usage:#define flock_trivial_usage
  7. //usage: "[-sxun] FD|{FILE [-c] PROG ARGS}"
  8. //usage:#define flock_full_usage "\n\n"
  9. //usage: "[Un]lock file descriptor, or lock FILE, run PROG\n"
  10. //usage: "\n -s Shared lock"
  11. //usage: "\n -x Exclusive lock (default)"
  12. //usage: "\n -u Unlock FD"
  13. //usage: "\n -n Fail rather than wait"
  14. #include <sys/file.h>
  15. #include "libbb.h"
  16. int flock_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  17. int flock_main(int argc UNUSED_PARAM, char **argv)
  18. {
  19. int mode, opt, fd;
  20. enum {
  21. OPT_s = (1 << 0),
  22. OPT_x = (1 << 1),
  23. OPT_n = (1 << 2),
  24. OPT_u = (1 << 3),
  25. OPT_c = (1 << 4),
  26. };
  27. #if ENABLE_LONG_OPTS
  28. static const char getopt_longopts[] ALIGN1 =
  29. "shared\0" No_argument "s"
  30. "exclusive\0" No_argument "x"
  31. "unlock\0" No_argument "u"
  32. "nonblock\0" No_argument "n"
  33. ;
  34. applet_long_options = getopt_longopts;
  35. #endif
  36. opt_complementary = "-1";
  37. opt = getopt32(argv, "+sxnu");
  38. argv += optind;
  39. if (argv[1]) {
  40. fd = open(argv[0], O_RDONLY|O_NOCTTY|O_CREAT, 0666);
  41. if (fd < 0 && errno == EISDIR)
  42. fd = open(argv[0], O_RDONLY|O_NOCTTY);
  43. if (fd < 0)
  44. bb_perror_msg_and_die("can't open '%s'", argv[0]);
  45. //TODO? close_on_exec_on(fd);
  46. } else {
  47. fd = xatoi_positive(argv[0]);
  48. }
  49. argv++;
  50. /* If it is "flock FILE -c PROG", then -c isn't caught by getopt32:
  51. * we use "+" in order to support "flock -opt FILE PROG -with-opts",
  52. * we need to remove -c by hand.
  53. * TODO: in upstream, -c 'PROG ARGS' means "run sh -c 'PROG ARGS'"
  54. */
  55. if (argv[0]
  56. && argv[0][0] == '-'
  57. && ( (argv[0][1] == 'c' && !argv[0][2])
  58. || (ENABLE_LONG_OPTS && strcmp(argv[0] + 1, "-command") == 0)
  59. )
  60. ) {
  61. argv++;
  62. }
  63. if (OPT_s == LOCK_SH && OPT_x == LOCK_EX && OPT_n == LOCK_NB && OPT_u == LOCK_UN) {
  64. /* With suitably matched constants, mode setting is much simpler */
  65. mode = opt & (LOCK_SH + LOCK_EX + LOCK_NB + LOCK_UN);
  66. if (!(mode & ~LOCK_NB))
  67. mode |= LOCK_EX;
  68. } else {
  69. if (opt & OPT_u)
  70. mode = LOCK_UN;
  71. else if (opt & OPT_s)
  72. mode = LOCK_SH;
  73. else
  74. mode = LOCK_EX;
  75. if (opt & OPT_n)
  76. mode |= LOCK_NB;
  77. }
  78. if (flock(fd, mode) != 0) {
  79. if (errno == EWOULDBLOCK)
  80. return EXIT_FAILURE;
  81. bb_perror_nomsg_and_die();
  82. }
  83. if (argv[0])
  84. return spawn_and_wait(argv);
  85. return EXIT_SUCCESS;
  86. }