2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (C) 1997 John D. Polstra. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY JOHN D. POLSTRA AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL JOHN D. POLSTRA OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
31 #include <sys/types.h>
43 static int acquire_lock(const char *name, int flags);
44 static void cleanup(void);
45 static void killed(int sig);
46 static void timeout(int sig);
47 static void usage(void);
48 static void wait_for_lock(const char *name);
50 static const char *lockname;
51 static int lockfd = -1;
53 static volatile sig_atomic_t timed_out;
56 * Execute an arbitrary command while holding a file lock.
59 main(int argc, char **argv)
61 int ch, flags, silent, status, waitsec;
65 flags = O_CREAT | O_RDONLY;
66 waitsec = -1; /* Infinite. */
67 while ((ch = getopt(argc, argv, "sknt:w")) != -1) {
81 waitsec = strtol(optarg, &endptr, 0);
82 if (*optarg == '\0' || *endptr != '\0' || waitsec < 0)
84 "invalid timeout \"%s\"", optarg);
88 flags = (flags & ~O_RDONLY) | O_WRONLY;
94 if (argc - optind < 2)
96 lockname = argv[optind++];
99 if (waitsec > 0) { /* Set up a timeout. */
100 struct sigaction act;
102 act.sa_handler = timeout;
103 sigemptyset(&act.sa_mask);
104 act.sa_flags = 0; /* Note that we do not set SA_RESTART. */
105 sigaction(SIGALRM, &act, NULL);
109 * If the "-k" option is not given, then we must not block when
110 * acquiring the lock. If we did, then the lock holder would
111 * unlink the file upon releasing the lock, and we would acquire
112 * a lock on a file with no directory entry. Then another
113 * process could come along and acquire the same lock. To avoid
114 * this problem, we separate out the actions of waiting for the
115 * lock to be available and of actually acquiring the lock.
117 * That approach produces behavior that is technically correct;
118 * however, it causes some performance & ordering problems for
119 * locks that have a lot of contention. First, it is unfair in
120 * the sense that a released lock isn't necessarily granted to
121 * the process that has been waiting the longest. A waiter may
122 * be starved out indefinitely. Second, it creates a thundering
123 * herd situation each time the lock is released.
125 * When the "-k" option is used, the unlink race no longer
126 * exists. In that case we can block while acquiring the lock,
127 * avoiding the separate step of waiting for the lock. This
128 * yields fairness and improved performance.
130 lockfd = acquire_lock(lockname, flags | O_NONBLOCK);
131 while (lockfd == -1 && !timed_out && waitsec != 0) {
133 lockfd = acquire_lock(lockname, flags);
135 wait_for_lock(lockname);
136 lockfd = acquire_lock(lockname, flags | O_NONBLOCK);
141 if (lockfd == -1) { /* We failed to acquire the lock. */
144 errx(EX_TEMPFAIL, "%s: already locked", lockname);
146 /* At this point, we own the lock. */
147 if (atexit(cleanup) == -1)
148 err(EX_OSERR, "atexit failed");
149 if ((child = fork()) == -1)
150 err(EX_OSERR, "cannot fork");
151 if (child == 0) { /* The child process. */
153 execvp(argv[0], argv);
157 /* This is the parent process. */
158 signal(SIGINT, SIG_IGN);
159 signal(SIGQUIT, SIG_IGN);
160 signal(SIGTERM, killed);
161 if (waitpid(child, &status, 0) == -1)
162 err(EX_OSERR, "waitpid failed");
163 return (WIFEXITED(status) ? WEXITSTATUS(status) : EX_SOFTWARE);
167 * Try to acquire a lock on the given file, creating the file if
168 * necessary. The flags argument is O_NONBLOCK or 0, depending on
169 * whether we should wait for the lock. Returns an open file descriptor
170 * on success, or -1 on failure.
173 acquire_lock(const char *name, int flags)
177 if ((fd = open(name, O_EXLOCK|flags, 0666)) == -1) {
178 if (errno == EAGAIN || errno == EINTR)
180 else if (errno == ENOENT && (flags & O_CREAT) == 0)
181 err(EX_UNAVAILABLE, "%s", name);
182 err(EX_CANTCREAT, "cannot open %s", name);
188 * Remove the lock file.
195 flock(lockfd, LOCK_UN);
201 * Signal handler for SIGTERM. Cleans up the lock file, then re-raises
209 signal(sig, SIG_DFL);
210 if (kill(getpid(), sig) == -1)
211 err(EX_OSERR, "kill failed");
215 * Signal handler for SIGALRM.
218 timeout(int sig __unused)
229 "usage: lockf [-kns] [-t seconds] file command [arguments]\n");
234 * Wait until it might be possible to acquire a lock on the given file.
235 * If the file does not exist, return immediately without creating it.
238 wait_for_lock(const char *name)
242 if ((fd = open(name, O_RDONLY|O_EXLOCK, 0666)) == -1) {
243 if (errno == ENOENT || errno == EINTR)
245 err(EX_CANTCREAT, "cannot open %s", name);