test structure too
[tridge/junkcode.git] / lockit.c
1 /* run a command with a lock held
2    tridge@samba.org, April 2002
3 */
4 #include <stdio.h>
5 #include <string.h>
6 #include <stdlib.h>
7 #include <unistd.h>
8 #include <fcntl.h>
9
10 static void usage(void)
11 {
12         printf("
13 lockit <lockfile> <command>
14
15 Runs a command with a lockfile held. If the lock is already held then blocks
16 waiting for the lock file to be released before continuing.
17
18 Note that after running the lockfile is left behind in the filesystem. This is 
19 correct behaviour.
20
21 The lock is inherited across exec but not fork
22 ");
23 }
24
25 /* lock a byte range in a open file */
26 static int lock_range(int fd, int offset, int len)
27 {
28         struct flock lock;
29
30         lock.l_type = F_WRLCK;
31         lock.l_whence = SEEK_SET;
32         lock.l_start = offset;
33         lock.l_len = len;
34         lock.l_pid = 0;
35         
36         return fcntl(fd,F_SETLKW,&lock);
37 }
38
39 int main(int argc, char *argv[])
40 {
41         char *lockfile;
42         int fd;
43         if (argc < 3) {
44                 usage();
45                 exit(1);
46         }
47
48         lockfile = argv[1];
49
50         fd = open(lockfile, O_CREAT|O_RDWR, 0644);
51         if (fd == -1) {
52                 perror(lockfile);
53                 exit(1);
54         }
55
56         if (lock_range(fd, 0, 1) != 0) {
57                 perror(lockfile);
58                 exit(2);
59         }
60
61         return execvp(argv[2], argv+2);
62 }