summaryrefslogtreecommitdiffstats
path: root/tools/locktest/testlk.c
blob: b392f711fcb9eea9edfc3b62e42ae7750bfa2c35 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#ifdef linux
#include <getopt.h>
#endif
#include <fcntl.h>

static void	usage(int exval);
static void	fatal(char *);

int
main(int argc, char **argv)
{
	unsigned long	start = 0, len = 0;
	struct flock	fl;
	int		c, fd, cmd, typ;
	char		*fname;

	typ = F_RDLCK;
	cmd = F_SETLK;

	while ((c = getopt(argc, argv, "bhrtw")) != EOF) {
		switch (c) {
		case 'h':
			usage(0);
		case 'r':
			cmd = F_SETLK;
			typ = F_RDLCK;
			break;
		case 'w':
			cmd = F_SETLK;
			typ = F_WRLCK;
			break;
		case 'b':
			cmd = F_SETLKW;
			typ = F_WRLCK;
			break;
		case 't':
			cmd = F_GETLK;
			break;
		case '?':
			usage(1);
		}
	}

	argc -= optind;
	argv += optind;

	if (argc <= 0 || argc > 3)
		usage(1);

	fname = argv[0];
	/* printf("TP\n"); */
	if (argc > 1)
		start = atoi(argv[1]);
	/* printf("TP\n"); */
	if (argc > 2)
		len   = atoi(argv[2]);
	/* printf("TP\n"); */

	if ((fd = open(fname, O_RDWR, 0644)) < 0)
		fatal(fname);

	/* printf("TP1\n"); */
	fl.l_type = typ;
	fl.l_whence = 0;
	fl.l_start = start;
	fl.l_len = len;

	if (fcntl(fd, cmd, &fl) < 0)
		fatal("fcntl");
	printf("fcntl: ok\n");
	
	/* printf("TP2\n"); */
	if (cmd == F_GETLK) {
		if (fl.l_type == F_UNLCK) {
			printf("%s: no conflicting lock\n", fname);
		} else {
			printf("%s: conflicting lock by %d on (%ld;%ld)\n",
				fname, fl.l_pid, fl.l_start, fl.l_len);
		}
		return 0;
	}

	/* printf("TP3\n"); */
	pause();
	return 0;
}

static void
usage(int exval)
{
	fprintf(stderr, "usage: testlk filename [start [len]]\n");
	exit(exval);
}

static void
fatal(char *msg)
{
	perror(msg);
	exit(2);
}