1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* Copyright (c) Matthew Wilcox for Hewlett Packard 2003
3 * Author: Matthew Wilcox
4 *
5 * Test Description:
6 * This test verifies that flock locks held on one fd conflict with flock
7 * locks held on a different fd.
8 *
9 * Test Steps:
10 * The process opens two file descriptors on the same file. It acquires
11 * an exclusive flock on the first descriptor, checks that attempting to
12 * acquire an flock on the second descriptor fails. Then it removes the
13 * first descriptor's lock and attempts to acquire an exclusive lock on
14 * the second descriptor.
15 */
16
17 #include <errno.h>
18 #include <sys/file.h>
19
20 #include "tst_test.h"
21
verify_flock(void)22 static void verify_flock(void)
23 {
24 int fd1, fd2;
25
26 fd1 = SAFE_OPEN("testfile", O_RDWR);
27 TEST(flock(fd1, LOCK_EX | LOCK_NB));
28 if (TST_RET != 0)
29 tst_res(TFAIL | TTERRNO, "First attempt to flock() failed");
30 else
31 tst_res(TPASS, "First attempt to flock() passed");
32
33 fd2 = SAFE_OPEN("testfile", O_RDWR);
34 TEST(flock(fd2, LOCK_EX | LOCK_NB));
35 if (TST_RET == -1)
36 tst_res(TPASS | TTERRNO, "Second attempt to flock() denied");
37 else
38 tst_res(TFAIL, "Second attempt to flock() succeeded!");
39
40 TEST(flock(fd1, LOCK_UN));
41 if (TST_RET != 0)
42 tst_res(TFAIL | TTERRNO, "Failed to unlock fd1");
43 else
44 tst_res(TPASS, "Unlocked fd1");
45
46 TEST(flock(fd2, LOCK_EX | LOCK_NB));
47 if (TST_RET != 0)
48 tst_res(TFAIL | TTERRNO, "Third attempt to flock() denied!");
49 else
50 tst_res(TPASS, "Third attempt to flock() succeeded");
51
52 SAFE_CLOSE(fd1);
53 SAFE_CLOSE(fd2);
54 }
55
setup(void)56 static void setup(void)
57 {
58 int fd;
59
60 fd = SAFE_OPEN("testfile", O_CREAT | O_TRUNC | O_RDWR, 0666);
61 SAFE_CLOSE(fd);
62 }
63
64 static struct tst_test test = {
65 .test_all = verify_flock,
66 .needs_tmpdir = 1,
67 .setup = setup,
68 };
69