2 * Copyright 2008, Axel Dörfler, axeld@pinc-software.de. All rights reserved.
3 * Distributed under the terms of the MIT License.
15 extern const char *__progname
;
17 const char* kTemporaryFile
= "/tmp/axels-lock-test";
23 return type
== F_RDLCK
? "shared" : type
== F_WRLCK
24 ? "exclusive" : "remove";
29 do_lock(int fd
, int type
, off_t start
, off_t length
)
31 printf("%s lock %Ld:%Ld\n", type_name(type
), start
, length
);
35 flock
.l_whence
= SEEK_SET
;
36 flock
.l_start
= start
;
38 if (fcntl(fd
, F_SETLK
, &flock
) != 0) {
39 fprintf(stderr
, "ERROR: %s lock %Ld:%Ld failed: %s\n", type_name(type
),
40 start
, length
, strerror(errno
));
49 shared_lock(int fd
, off_t start
, off_t length
)
51 return do_lock(fd
, F_RDLCK
, start
, length
);
56 exclusive_lock(int fd
, off_t start
, off_t length
)
58 return do_lock(fd
, F_WRLCK
, start
, length
);
63 remove_lock(int fd
, off_t start
, off_t length
)
65 return do_lock(fd
, F_UNLCK
, start
, length
);
72 puts("wait for <enter>...");
74 fgets(buffer
, sizeof(buffer
), stdin
);
81 fprintf(stderr
, "usage: %s [shared|exclusive|unlock <start> <length>] "
82 "[wait] [...]\n", __progname
);
88 is_command(const char* op
, const char* command1
, const char* command2
)
90 int length
= strlen(op
);
94 return command1
!= NULL
&& !strncmp(op
, command1
, length
)
95 || command2
!= NULL
&& !strncmp(op
, command2
, length
);
100 main(int argc
, char** argv
)
102 int fd
= open(kTemporaryFile
, O_CREAT
| O_RDWR
, 0644);
104 fprintf(stderr
, "Could not create lock file: %s\n", strerror(errno
));
109 const char* op
= argv
[1];
110 if (is_command(op
, "wait", NULL
)) {
119 off_t start
= strtoll(argv
[2], NULL
, 0);
120 off_t length
= strtoll(argv
[3], NULL
, 0);
122 if (is_command(op
, "read", "shared"))
124 else if (is_command(op
, "write", "exclusive"))
126 else if (is_command(op
, "unlock", "remove"))
131 do_lock(fd
, type
, start
, length
);