2 * Copyright 2005, Axel Dörfler, axeld@pinc-software.de.
3 * Distributed under the terms of the MIT License.
21 try_to_lock(void *_fd
)
23 intptr_t fd
= (intptr_t)_fd
;
25 struct flock flock
= {
26 F_RDLCK
, // shared lock
29 0, // until the end of the file
33 if (fcntl(fd
, F_SETLK
, &flock
) == 0) {
34 fprintf(stderr
, "a. Could lock file!\n");
37 puts("test a passed.");
41 // wait for lock to become free
43 if (fcntl(fd
, F_SETLKW
, &flock
) == -1) {
44 fprintf(stderr
, "b. Could not lock file: %s\n", strerror(errno
));
47 puts("test b passed.");
49 flock
.l_type
= F_UNLCK
;
51 if (fcntl(fd
, F_SETLK
, &flock
) == -1) {
52 fprintf(stderr
, "c. Could not unlock file: %s\n", strerror(errno
));
55 puts("test c passed.");
62 main(int argc
, char **argv
)
64 intptr_t fd
= open("/etc/passwd", O_RDONLY
);
66 fprintf(stderr
, "could not open file: %s\n", strerror(errno
));
70 struct flock flock
= {
71 F_WRLCK
, // exclusive lock
72 SEEK_SET
, // lock whole file
78 if (fcntl(fd
, F_SETLK
, &flock
) == 0) {
79 fprintf(stderr
, "0. Could lock file exclusively without write access!\n");
82 puts("test 0 passed.");
84 flock
.l_type
= F_RDLCK
;
85 // shared locks should be allowed
87 if (fcntl(fd
, F_SETLK
, &flock
) == -1) {
88 fprintf(stderr
, "1. Could not lock file: %s\n", strerror(errno
));
91 puts("test 1 passed.");
95 fd
= open("/etc/passwd", O_RDWR
);
97 fprintf(stderr
, "could not open file: %s\n", strerror(errno
));
101 flock
.l_type
= F_WRLCK
;
105 if (fcntl(fd
, F_SETLK
, &flock
) == -1) {
106 fprintf(stderr
, "2. Could not lock file: %s\n", strerror(errno
));
109 puts("test 2 passed.");
113 if (fcntl(fd
, F_SETLK
, &flock
) == -1) {
114 fprintf(stderr
, "3. Could not lock file: %s\n", strerror(errno
));
117 puts("test 3 passed.");
121 if (fcntl(fd
, F_SETLK
, &flock
) == 0) {
122 fprintf(stderr
, "4. Could lock file exclusively on locked region!\n");
125 puts("test 4 passed.");
127 flock
.l_type
= F_UNLCK
;
130 if (fcntl(fd
, F_SETLK
, &flock
) == -1) {
131 fprintf(stderr
, "5. Could not unlock file: %s\n", strerror(errno
));
134 puts("test 5 passed.");
136 flock
.l_type
= F_WRLCK
;
139 if (fcntl(fd
, F_SETLK
, &flock
) == -1) {
140 fprintf(stderr
, "6. Could not lock file: %s\n", strerror(errno
));
143 puts("test 6 passed.");
145 thread_id thread
= spawn_thread(try_to_lock
, "try", B_NORMAL_PRIORITY
, (void *)fd
);
147 fprintf(stderr
, "Could not spawn thread: %s\n", strerror(thread
));
150 resume_thread(thread
);
153 snooze(100000); // 0.1s
156 flock
.l_type
= F_UNLCK
;
159 if (fcntl(fd
, F_SETLK
, &flock
) == -1) {
160 fprintf(stderr
, "7. Could not unlock file: %s\n", strerror(errno
));
163 puts("test 7 passed.");
166 wait_for_thread(thread
, &returnCode
);