chiark / gitweb /
found old non-after-fstatting version lying about, for historical interest only
[chiark-utils.git] / cprogs / with-lock-ex.c
1 /*
2  * File locker
3  *
4  * Usage: with-lock-ex -<mode> <lockfile> <command> <args>...
5  *
6  * modes are
7  *  w    wait for the lock
8  *  f    fail if the lock cannot be acquired
9  *  q    silently do nothing if the lock cannot be acquired
10  *
11  * with-lock-ex will open and lock the lockfile for writing and
12  * then feed the remainder of its arguments to exec(2); when
13  * that process terminates the fd will be closed and the file
14  * unlocked automatically by the kernel.
15  *
16  * If invoked as with-lock, behaves like with-lock-ex -f (for backward
17  * compatibility with an earlier version).
18  *
19  * This file written by me, Ian Jackson, in 1993, 1994, 1995, 1996,
20  * 1998, 1999.  I hereby place it in the public domain.
21  */
22
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <string.h>
29 #include <sys/stat.h>
30
31 static const char *cmd;
32
33 static void fail(const char *why) __attribute__((noreturn));
34
35 static void fail(const char *why) {
36   fprintf(stderr,"with-lock-ex %s: %s: %s\n",cmd,why,strerror(errno));
37   exit(255);
38 }
39
40 int main(int argc, char **argv) {
41   int fd, mode, um;
42   long cloexec;
43   struct flock fl;
44   const char *p;
45
46   if (argc >= 3 && !strcmp((p= strrchr(argv[0],'/')) ? ++p : argv[0], "with-lock")) {
47     mode= 'f';
48   } else if (argc < 4 || argv[1][0] != '-' || argv[1][2] ||
49              ((mode= argv[1][1]) != 'w' && mode != 'q' && mode != 'f')) {
50     fputs("usage: with-lock-ex -w|-q|-f <lockfile> <command> <args>...\n"
51           "       with-lock             <lockfile> <command> <args>...\n",
52           stderr);
53     exit(255);
54   } else {
55     argv++; argc--;
56   }
57   cmd= argv[2];
58   um= umask(0777); if (um==-1) fail("find umask");
59   if (umask(um)==-1) fail("reset umask");
60   
61   fd= open(argv[1],O_RDWR|O_CREAT,0666&~(um|((um&0222)<<1))); if (fd<0) fail(argv[1]);
62   
63   for (;;) {
64     fl.l_type= F_WRLCK;
65     fl.l_whence= SEEK_SET;
66     fl.l_start= 0;
67     fl.l_len= 1;
68     if (fcntl(fd, mode=='w' ? F_SETLKW : F_SETLK, &fl) != -1) break;
69     if (mode=='q' && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EBUSY)) exit(0);
70     if (errno != EINTR) fail("could not acquire lock");
71   }
72
73   cloexec= fcntl(fd, F_GETFD); if (cloexec==-1) fail("fcntl F_GETFD");
74   cloexec &= ~1;
75   if (fcntl(fd, F_SETFD, cloexec)==-1) fail("fcntl F_SETFD");
76
77   execvp(cmd,argv+2);
78   fail("unable to execute command");
79 }