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