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