xref: /freebsd/usr.bin/lockf/lockf.c (revision 952d112864d8008aa87278a30a539d888a8493cd)
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  * $Id: lockf.c,v 1.4 1997/02/22 19:55:54 peter Exp $
26  */
27 
28 #include <sys/types.h>
29 #include <sys/wait.h>
30 
31 #include <err.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <signal.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <sysexits.h>
38 #include <unistd.h>
39 
40 static int acquire_lock(const char *name);
41 static void cleanup(void);
42 static void killed(int sig);
43 static void timeout(int sig);
44 static void usage(void);
45 static void wait_for_lock(const char *name);
46 
47 static const char *lockname;
48 static volatile sig_atomic_t timed_out;
49 
50 /*
51  * Execute an arbitrary command while holding a file lock.
52  */
53 int
54 main(int argc, char **argv)
55 {
56     int ch;
57     int lockfd;
58     int silent;
59     int status;
60     int waitsec;
61     pid_t child;
62 
63     silent = 0;
64     waitsec = -1;	/* Infinite. */
65     while ((ch = getopt(argc, argv, "st:")) != -1) {
66 	switch (ch) {
67 
68 	case 's':
69 	    silent = 1;
70 	    break;
71 
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, "invalid timeout \"%s\"", optarg);
78 	    }
79 	    break;
80 
81 	default:
82 	    usage();
83 	}
84     }
85     if (argc - optind < 2)
86 	usage();
87     lockname = argv[optind++];
88     argc -= optind;
89     argv += optind;
90 
91     if (waitsec > 0) {		/* Set up a timeout. */
92 	struct sigaction act;
93 
94 	act.sa_handler = timeout;
95 	sigemptyset(&act.sa_mask);
96 	act.sa_flags = 0;	/* Note that we do not set SA_RESTART. */
97 
98 	sigaction(SIGALRM, &act, NULL);
99 	alarm(waitsec);
100     }
101 
102     lockfd = acquire_lock(lockname);
103     while (lockfd == -1 && !timed_out && waitsec != 0) {
104 	wait_for_lock(lockname);
105 	lockfd = acquire_lock(lockname);
106     }
107 
108     if (waitsec > 0)
109 	alarm(0);
110 
111     if (lockfd == -1) {		/* We failed to acquire the lock. */
112 	if (silent)
113 	    exit(EX_TEMPFAIL);
114 	errx(EX_TEMPFAIL, "%s: already locked", lockname);
115     }
116 
117     /* At this point, we own the lock. */
118 
119     if (atexit(cleanup) == -1)
120 	err(EX_OSERR, "atexit failed");
121 
122     if ((child = fork()) == -1)
123 	err(EX_OSERR, "cannot fork");
124 
125     if (child == 0) {	/* The child process. */
126 	close(lockfd);
127 	execvp(argv[0], argv);
128 	perror(argv[0]);
129 	_exit(1);
130     }
131 
132     /* This is the parent process. */
133 
134     signal(SIGINT, SIG_IGN);
135     signal(SIGQUIT, SIG_IGN);
136     signal(SIGTERM, killed);
137 
138     if (waitpid(child, &status, 0) == -1)
139 	err(EX_OSERR, "waitpid failed");
140 
141     return WIFEXITED(status) ? WEXITSTATUS(status) : 1;
142 }
143 
144 /*
145  * Try to acquire a lock on the given file, but don't wait for it.  Returns
146  * an open file descriptor on success, or -1 on failure.
147  */
148 static int
149 acquire_lock(const char *name)
150 {
151     int fd;
152 
153     if ((fd = open(name, O_RDONLY|O_CREAT|O_EXLOCK|O_NONBLOCK, 0666)) == -1) {
154 	if (errno == EAGAIN || errno == EINTR)
155 	    return -1;
156 	err(EX_CANTCREAT, "cannot open %s", name);
157     }
158     return fd;
159 }
160 
161 /*
162  * Remove the lock file.
163  */
164 static void
165 cleanup(void)
166 {
167     unlink(lockname);
168 }
169 
170 /*
171  * Signal handler for SIGTERM.  Cleans up the lock file, then re-raises
172  * the signal.
173  */
174 static void
175 killed(int sig)
176 {
177     cleanup();
178     signal(sig, SIG_DFL);
179     if (kill(getpid(), sig) == -1)
180 	err(EX_OSERR, "kill failed");
181 }
182 
183 /*
184  * Signal handler for SIGALRM.
185  */
186 static void
187 timeout(int sig)
188 {
189     timed_out = 1;
190 }
191 
192 static void
193 usage(void)
194 {
195     errx(EX_USAGE, "usage: lockf [-s] [-t seconds] file command [arguments]");
196 }
197 
198 /*
199  * Wait until it might be possible to acquire a lock on the given file.
200  */
201 static void
202 wait_for_lock(const char *name)
203 {
204     int fd;
205 
206     if ((fd = open(name, O_RDONLY|O_EXLOCK)) == -1) {
207 	if (errno == ENOENT || errno == EINTR)
208 	    return;
209 	err(EX_CANTCREAT, "cannot open %s", name);
210     }
211     close(fd);
212     return;
213 }
214