xref: /freebsd/usr.bin/lockf/lockf.c (revision aa0a1e58)
1 /*
2  * Copyright (C) 1997 John D. Polstra.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY JOHN D. POLSTRA AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL JOHN D. POLSTRA OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  */
25 
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
28 
29 #include <sys/types.h>
30 #include <sys/wait.h>
31 
32 #include <err.h>
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <signal.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <sysexits.h>
39 #include <unistd.h>
40 
41 static int acquire_lock(const char *name, int flags);
42 static void cleanup(void);
43 static void killed(int sig);
44 static void timeout(int sig);
45 static void usage(void);
46 static void wait_for_lock(const char *name);
47 
48 static const char *lockname;
49 static int lockfd = -1;
50 static int keep;
51 static volatile sig_atomic_t timed_out;
52 
53 /*
54  * Execute an arbitrary command while holding a file lock.
55  */
56 int
57 main(int argc, char **argv)
58 {
59 	int ch, silent, status, waitsec;
60 	pid_t child;
61 
62 	silent = keep = 0;
63 	waitsec = -1;	/* Infinite. */
64 	while ((ch = getopt(argc, argv, "skt:")) != -1) {
65 		switch (ch) {
66 		case 'k':
67 			keep = 1;
68 			break;
69 		case 's':
70 			silent = 1;
71 			break;
72 		case 't':
73 		{
74 			char *endptr;
75 			waitsec = strtol(optarg, &endptr, 0);
76 			if (*optarg == '\0' || *endptr != '\0' || waitsec < 0)
77 				errx(EX_USAGE,
78 				    "invalid timeout \"%s\"", optarg);
79 		}
80 			break;
81 		default:
82 			usage();
83 		}
84 	}
85 	if (argc - optind < 2)
86 		usage();
87 	lockname = argv[optind++];
88 	argc -= optind;
89 	argv += optind;
90 	if (waitsec > 0) {		/* Set up a timeout. */
91 		struct sigaction act;
92 
93 		act.sa_handler = timeout;
94 		sigemptyset(&act.sa_mask);
95 		act.sa_flags = 0;	/* Note that we do not set SA_RESTART. */
96 		sigaction(SIGALRM, &act, NULL);
97 		alarm(waitsec);
98 	}
99 	/*
100 	 * If the "-k" option is not given, then we must not block when
101 	 * acquiring the lock.  If we did, then the lock holder would
102 	 * unlink the file upon releasing the lock, and we would acquire
103 	 * a lock on a file with no directory entry.  Then another
104 	 * process could come along and acquire the same lock.  To avoid
105 	 * this problem, we separate out the actions of waiting for the
106 	 * lock to be available and of actually acquiring the lock.
107 	 *
108 	 * That approach produces behavior that is technically correct;
109 	 * however, it causes some performance & ordering problems for
110 	 * locks that have a lot of contention.  First, it is unfair in
111 	 * the sense that a released lock isn't necessarily granted to
112 	 * the process that has been waiting the longest.  A waiter may
113 	 * be starved out indefinitely.  Second, it creates a thundering
114 	 * herd situation each time the lock is released.
115 	 *
116 	 * When the "-k" option is used, the unlink race no longer
117 	 * exists.  In that case we can block while acquiring the lock,
118 	 * avoiding the separate step of waiting for the lock.  This
119 	 * yields fairness and improved performance.
120 	 */
121 	lockfd = acquire_lock(lockname, O_NONBLOCK);
122 	while (lockfd == -1 && !timed_out && waitsec != 0) {
123 		if (keep)
124 			lockfd = acquire_lock(lockname, 0);
125 		else {
126 			wait_for_lock(lockname);
127 			lockfd = acquire_lock(lockname, O_NONBLOCK);
128 		}
129 	}
130 	if (waitsec > 0)
131 		alarm(0);
132 	if (lockfd == -1) {		/* We failed to acquire the lock. */
133 		if (silent)
134 			exit(EX_TEMPFAIL);
135 		errx(EX_TEMPFAIL, "%s: already locked", lockname);
136 	}
137 	/* At this point, we own the lock. */
138 	if (atexit(cleanup) == -1)
139 		err(EX_OSERR, "atexit failed");
140 	if ((child = fork()) == -1)
141 		err(EX_OSERR, "cannot fork");
142 	if (child == 0) {	/* The child process. */
143 		close(lockfd);
144 		execvp(argv[0], argv);
145 		warn("%s", argv[0]);
146 		_exit(1);
147 	}
148 	/* This is the parent process. */
149 	signal(SIGINT, SIG_IGN);
150 	signal(SIGQUIT, SIG_IGN);
151 	signal(SIGTERM, killed);
152 	if (waitpid(child, &status, 0) == -1)
153 		err(EX_OSERR, "waitpid failed");
154 	return (WIFEXITED(status) ? WEXITSTATUS(status) : EX_SOFTWARE);
155 }
156 
157 /*
158  * Try to acquire a lock on the given file, creating the file if
159  * necessary.  The flags argument is O_NONBLOCK or 0, depending on
160  * whether we should wait for the lock.  Returns an open file descriptor
161  * on success, or -1 on failure.
162  */
163 static int
164 acquire_lock(const char *name, int flags)
165 {
166 	int fd;
167 
168 	if ((fd = open(name, O_RDONLY|O_CREAT|O_EXLOCK|flags, 0666)) == -1) {
169 		if (errno == EAGAIN || errno == EINTR)
170 			return (-1);
171 		err(EX_CANTCREAT, "cannot open %s", name);
172 	}
173 	return (fd);
174 }
175 
176 /*
177  * Remove the lock file.
178  */
179 static void
180 cleanup(void)
181 {
182 
183 	if (keep)
184 		flock(lockfd, LOCK_UN);
185 	else
186 		unlink(lockname);
187 }
188 
189 /*
190  * Signal handler for SIGTERM.  Cleans up the lock file, then re-raises
191  * the signal.
192  */
193 static void
194 killed(int sig)
195 {
196 
197 	cleanup();
198 	signal(sig, SIG_DFL);
199 	if (kill(getpid(), sig) == -1)
200 		err(EX_OSERR, "kill failed");
201 }
202 
203 /*
204  * Signal handler for SIGALRM.
205  */
206 static void
207 timeout(int sig __unused)
208 {
209 
210 	timed_out = 1;
211 }
212 
213 static void
214 usage(void)
215 {
216 
217 	fprintf(stderr,
218 	    "usage: lockf [-ks] [-t seconds] file command [arguments]\n");
219 	exit(EX_USAGE);
220 }
221 
222 /*
223  * Wait until it might be possible to acquire a lock on the given file.
224  * If the file does not exist, return immediately without creating it.
225  */
226 static void
227 wait_for_lock(const char *name)
228 {
229 	int fd;
230 
231 	if ((fd = open(name, O_RDONLY|O_EXLOCK, 0666)) == -1) {
232 		if (errno == ENOENT || errno == EINTR)
233 			return;
234 		err(EX_CANTCREAT, "cannot open %s", name);
235 	}
236 	close(fd);
237 }
238