2 * Copyright (C) 2010 Timo Teras <timo.teras@iki.fi>
4 * This is free software, licensed under the GNU General Public License v2.
7 //usage:#define flock_trivial_usage
8 //usage: "[-sxun] FD|{FILE [-c] PROG ARGS}"
9 //usage:#define flock_full_usage "\n\n"
10 //usage: "[Un]lock file descriptor, or lock FILE, run PROG\n"
11 //usage: "\n -s Shared lock"
12 //usage: "\n -x Exclusive lock (default)"
13 //usage: "\n -u Unlock FD"
14 //usage: "\n -n Fail rather than wait"
19 int flock_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
20 int flock_main(int argc UNUSED_PARAM, char **argv)
32 static const char getopt_longopts[] ALIGN1 =
33 "shared\0" No_argument "s"
34 "exclusive\0" No_argument "x"
35 "unlock\0" No_argument "u"
36 "nonblock\0" No_argument "n"
38 applet_long_options = getopt_longopts;
40 opt_complementary = "-1";
42 opt = getopt32(argv, "+sxnu");
46 fd = open(argv[0], O_RDONLY|O_NOCTTY|O_CREAT, 0666);
47 if (fd < 0 && errno == EISDIR)
48 fd = open(argv[0], O_RDONLY|O_NOCTTY);
50 bb_perror_msg_and_die("can't open '%s'", argv[0]);
51 //TODO? close_on_exec_on(fd);
53 fd = xatoi_positive(argv[0]);
57 /* If it is "flock FILE -c PROG", then -c isn't caught by getopt32:
58 * we use "+" in order to support "flock -opt FILE PROG -with-opts",
59 * we need to remove -c by hand.
63 && ( (argv[0][1] == 'c' && !argv[0][2])
64 || (ENABLE_LONG_OPTS && strcmp(argv[0] + 1, "-command") == 0)
69 bb_error_msg_and_die("-c takes only one argument");
73 if (OPT_s == LOCK_SH && OPT_x == LOCK_EX && OPT_n == LOCK_NB && OPT_u == LOCK_UN) {
74 /* With suitably matched constants, mode setting is much simpler */
75 mode = opt & (LOCK_SH + LOCK_EX + LOCK_NB + LOCK_UN);
76 if (!(mode & ~LOCK_NB))
89 if (flock(fd, mode) != 0) {
90 if (errno == EWOULDBLOCK)
92 bb_perror_nomsg_and_die();
98 /* -c 'PROG ARGS' means "run sh -c 'PROG ARGS'" */
100 argv[0] = (char*)get_shell_name();
101 argv[1] = (char*)"-c";
102 /* argv[2] = "PROG ARGS"; */
103 /* argv[3] = NULL; */
105 rc = spawn_and_wait(argv);
107 bb_simple_perror_msg(argv[0]);