2 * Copyright (C) 2010 Timo Teras <timo.teras@iki.fi>
4 * This is free software, licensed under the GNU General Public License v2.
9 int flock_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
10 int flock_main(int argc UNUSED_PARAM, char **argv)
22 static const char getopt_longopts[] ALIGN1 =
23 "shared\0" No_argument "s"
24 "exclusive\0" No_argument "x"
25 "unlock\0" No_argument "u"
26 "nonblock\0" No_argument "n"
28 applet_long_options = getopt_longopts;
30 opt_complementary = "-1";
32 opt = getopt32(argv, "+sxnu");
36 fd = open(argv[0], O_RDONLY|O_NOCTTY|O_CREAT, 0666);
37 if (fd < 0 && errno == EISDIR)
38 fd = open(argv[0], O_RDONLY|O_NOCTTY);
40 bb_perror_msg_and_die("can't open '%s'", argv[0]);
41 //TODO? close_on_exec_on(fd);
43 fd = xatoi_positive(argv[0]);
47 /* If it is "flock FILE -c PROG", then -c isn't caught by getopt32:
48 * we use "+" in order to support "flock -opt FILE PROG -with-opts",
49 * we need to remove -c by hand.
50 * TODO: in upstream, -c 'PROG ARGS' means "run sh -c 'PROG ARGS'"
54 && ( (argv[0][1] == 'c' && !argv[0][2])
55 || (ENABLE_LONG_OPTS && strcmp(argv[0] + 1, "-command") == 0)
61 if (OPT_s == LOCK_SH && OPT_x == LOCK_EX && OPT_n == LOCK_NB && OPT_u == LOCK_UN) {
62 /* With suitably matched constants, mode setting is much simpler */
63 mode = opt & (LOCK_SH + LOCK_EX + LOCK_NB + LOCK_UN);
64 if (!(mode & ~LOCK_NB))
77 if (flock(fd, mode) != 0) {
78 if (errno == EWOULDBLOCK)
80 bb_perror_nomsg_and_die();
84 return spawn_and_wait(argv);