flock.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. #include <sys/file.h>
  7. #include "libbb.h"
  8. int flock_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9. int flock_main(int argc UNUSED_PARAM, char **argv)
  10. {
  11. int mode, opt, fd;
  12. enum {
  13. OPT_s = (1 << 0),
  14. OPT_x = (1 << 1),
  15. OPT_n = (1 << 2),
  16. OPT_u = (1 << 3),
  17. OPT_c = (1 << 4),
  18. };
  19. #if ENABLE_LONG_OPTS
  20. static const char getopt_longopts[] ALIGN1 =
  21. "shared\0" No_argument "s"
  22. "exclusive\0" No_argument "x"
  23. "unlock\0" No_argument "u"
  24. "nonblock\0" No_argument "n"
  25. ;
  26. applet_long_options = getopt_longopts;
  27. #endif
  28. opt_complementary = "-1";
  29. opt = getopt32(argv, "+sxnu");
  30. argv += optind;
  31. if (argv[1]) {
  32. fd = open(argv[0], O_RDONLY|O_NOCTTY|O_CREAT, 0666);
  33. if (fd < 0 && errno == EISDIR)
  34. fd = open(argv[0], O_RDONLY|O_NOCTTY);
  35. if (fd < 0)
  36. bb_perror_msg_and_die("can't open '%s'", argv[0]);
  37. //TODO? close_on_exec_on(fd);
  38. } else {
  39. fd = xatoi_u(argv[0]);
  40. }
  41. argv++;
  42. /* If it is "flock FILE -c PROG", then -c isn't caught by getopt32:
  43. * we use "+" in order to support "flock -opt FILE PROG -with-opts",
  44. * we need to remove -c by hand.
  45. * TODO: in upstream, -c 'PROG ARGS' means "run sh -c 'PROG ARGS'"
  46. */
  47. if (argv[0]
  48. && argv[0][0] == '-'
  49. && ( (argv[0][1] == 'c' && !argv[0][2])
  50. || (ENABLE_LONG_OPTS && strcmp(argv[0] + 1, "-command") == 0)
  51. )
  52. ) {
  53. argv++;
  54. }
  55. if (OPT_s == LOCK_SH && OPT_x == LOCK_EX && OPT_n == LOCK_NB && OPT_u == LOCK_UN) {
  56. /* With suitably matched constants, mode setting is much simpler */
  57. mode = opt & (LOCK_SH + LOCK_EX + LOCK_NB + LOCK_UN);
  58. if (!(mode & ~LOCK_NB))
  59. mode |= LOCK_EX;
  60. } else {
  61. if (opt & OPT_u)
  62. mode = LOCK_UN;
  63. else if (opt & OPT_s)
  64. mode = LOCK_SH;
  65. else
  66. mode = LOCK_EX;
  67. if (opt & OPT_n)
  68. mode |= LOCK_NB;
  69. }
  70. if (flock(fd, mode) != 0) {
  71. if (errno == EWOULDBLOCK)
  72. return EXIT_FAILURE;
  73. bb_perror_nomsg_and_die();
  74. }
  75. if (argv[0])
  76. return spawn_and_wait(argv);
  77. return EXIT_SUCCESS;
  78. }