]> git.decadent.org.uk Git - nfs-utils.git/blob - tools/locktest/testlk.c
47eb40acf47a8e0ab7a2286e4dc17872968cf012
[nfs-utils.git] / tools / locktest / testlk.c
1 #include "config.h"
2
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <unistd.h>
6 #ifdef linux
7 #include <getopt.h>
8 #endif
9 #include <fcntl.h>
10
11 static void     usage(int exval);
12 static void     fatal(char *);
13
14 int
15 main(int argc, char **argv)
16 {
17         unsigned long   start = 0, len = 0;
18         struct flock    fl;
19         int             c, fd, cmd, typ;
20         char            *fname;
21
22         typ = F_RDLCK;
23         cmd = F_SETLK;
24
25         while ((c = getopt(argc, argv, "bhrtw")) != EOF) {
26                 switch (c) {
27                 case 'h':
28                         usage(0);
29                 case 'r':
30                         cmd = F_SETLK;
31                         typ = F_RDLCK;
32                         break;
33                 case 'w':
34                         cmd = F_SETLK;
35                         typ = F_WRLCK;
36                         break;
37                 case 'b':
38                         cmd = F_SETLKW;
39                         typ = F_WRLCK;
40                         break;
41                 case 't':
42                         cmd = F_GETLK;
43                         break;
44                 case '?':
45                         usage(1);
46                 }
47         }
48
49         argc -= optind;
50         argv += optind;
51
52         if (argc <= 0 || argc > 3)
53                 usage(1);
54
55         fname = argv[0];
56         /* printf("TP\n"); */
57         if (argc > 1)
58                 start = atoi(argv[1]);
59         /* printf("TP\n"); */
60         if (argc > 2)
61                 len   = atoi(argv[2]);
62         /* printf("TP\n"); */
63
64         if ((fd = open(fname, O_RDWR, 0644)) < 0)
65                 fatal(fname);
66
67         /* printf("TP1\n"); */
68         fl.l_type = typ;
69         fl.l_whence = 0;
70         fl.l_start = start;
71         fl.l_len = len;
72
73         if (fcntl(fd, cmd, &fl) < 0)
74                 fatal("fcntl");
75         printf("fcntl: ok\n");
76         
77         /* printf("TP2\n"); */
78         if (cmd == F_GETLK) {
79                 if (fl.l_type == F_UNLCK) {
80                         printf("%s: no conflicting lock\n", fname);
81                 } else {
82                         printf("%s: conflicting lock by %d on (%ld;%ld)\n",
83                                 fname, fl.l_pid, fl.l_start, fl.l_len);
84                 }
85                 return 0;
86         }
87
88         /* printf("TP3\n"); */
89         pause();
90         return 0;
91 }
92
93 static void
94 usage(int exval)
95 {
96         fprintf(stderr, "usage: testlk filename [start [len]]\n");
97         exit(exval);
98 }
99
100 static void
101 fatal(char *msg)
102 {
103         perror(msg);
104         exit(2);
105 }