| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include <sys/file.h> |
| 4 |
#include <unistd.h> |
| 5 |
|
| 6 |
#include "errno-util.h" |
| 7 |
#include "fd-util.h" |
| 8 |
#include "lock-util.h" |
| 9 |
#include "rm-rf.h" |
| 10 |
#include "tests.h" |
| 11 |
#include "time-util.h" |
| 12 |
#include "tmpfile-util.h" |
| 13 |
|
| 14 |
TEST(make_lock_file) { |
| 15 |
_cleanup_(rm_rf_physical_and_freep) char *t = NULL; |
| 16 |
_cleanup_close_ int tfd = -EBADF; |
| 17 |
_cleanup_(release_lock_file) LockFile lock1 = LOCK_FILE_INIT, lock2 = LOCK_FILE_INIT; |
| 18 |
|
| 19 |
assert_se((tfd = mkdtemp_open(NULL, 0, &t)) >= 0); |
| 20 |
|
| 21 |
assert_se(make_lock_file_at(tfd, "lock", LOCK_EX, &lock1) >= 0); |
| 22 |
assert_se(faccessat(tfd, "lock", F_OK, 0) >= 0); |
| 23 |
assert_se(make_lock_file_at(tfd, "lock", LOCK_EX|LOCK_NB, &lock2) == -EBUSY); |
| 24 |
release_lock_file(&lock1); |
| 25 |
assert_se(RET_NERRNO(faccessat(tfd, "lock", F_OK, 0)) == -ENOENT); |
| 26 |
assert_se(make_lock_file_at(tfd, "lock", LOCK_EX, &lock2) >= 0); |
| 27 |
release_lock_file(&lock2); |
| 28 |
assert_se(make_lock_file_at(tfd, "lock", LOCK_SH, &lock1) >= 0); |
| 29 |
assert_se(faccessat(tfd, "lock", F_OK, 0) >= 0); |
| 30 |
assert_se(make_lock_file_at(tfd, "lock", LOCK_SH, &lock2) >= 0); |
| 31 |
release_lock_file(&lock1); |
| 32 |
assert_se(faccessat(tfd, "lock", F_OK, 0) >= 0); |
| 33 |
release_lock_file(&lock2); |
| 34 |
|
| 35 |
assert_se(fchdir(tfd) >= 0); |
| 36 |
assert_se(make_lock_file_at(tfd, "lock", LOCK_EX, &lock1) >= 0); |
| 37 |
assert_se(make_lock_file("lock", LOCK_EX|LOCK_NB, &lock2) == -EBUSY); |
| 38 |
} |
| 39 |
|
| 40 |
static void test_lock_generic_with_timeout_for_type(LockType type) { |
| 41 |
_cleanup_(rm_rf_physical_and_freep) char *t = NULL; |
| 42 |
_cleanup_close_ int tfd = -EBADF, tfd2 = -EBADF; |
| 43 |
|
| 44 |
tfd = mkdtemp_open(NULL, 0, &t); |
| 45 |
assert_se(tfd >= 0); |
| 46 |
|
| 47 |
tfd2 = fd_reopen(tfd, O_CLOEXEC|O_DIRECTORY); |
| 48 |
assert_se(tfd2 >= 0); |
| 49 |
|
| 50 |
assert_se(lock_generic(tfd, LOCK_BSD, LOCK_EX) >= 0); |
| 51 |
assert_se(lock_generic(tfd2, LOCK_BSD, LOCK_EX|LOCK_NB) == -EWOULDBLOCK); |
| 52 |
|
| 53 |
usec_t start = now(CLOCK_MONOTONIC); |
| 54 |
assert_se(lock_generic_with_timeout(tfd2, LOCK_BSD, LOCK_EX, 200 * USEC_PER_MSEC) == -ETIMEDOUT); |
| 55 |
assert_se(usec_sub_unsigned(now(CLOCK_MONOTONIC), start) >= 200 * USEC_PER_MSEC); |
| 56 |
|
| 57 |
assert_se(lock_generic(tfd, LOCK_BSD, LOCK_UN) >= 0); |
| 58 |
assert_se(lock_generic_with_timeout(tfd2, LOCK_BSD, LOCK_EX, 200 * USEC_PER_MSEC) == 0); |
| 59 |
assert_se(lock_generic(tfd, LOCK_BSD, LOCK_EX|LOCK_NB) == -EWOULDBLOCK); |
| 60 |
} |
| 61 |
|
| 62 |
TEST(lock_generic_with_timeout) { |
| 63 |
test_lock_generic_with_timeout_for_type(LOCK_BSD); |
| 64 |
test_lock_generic_with_timeout_for_type(LOCK_UNPOSIX); |
| 65 |
} |
| 66 |
|
| 67 |
DEFINE_TEST_MAIN(LOG_INFO); |