• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* Copyright (c) Wipro Technologies Ltd, 2002.  All Rights Reserved.
3  * Copyright (c) Linux Test Project, 2003-2021
4  * Author: Vatsal Avasthi
5  */
6 
7 /*\
8  * [Description]
9  *
10  * Test verifies that flock() behavior with different locking combinations along
11  * with LOCK_SH and LOCK_EX:
12  *
13  * - flock() succeeded in acquiring shared lock on shared lock file.
14  * - flock() failed to acquire exclusive lock on shared lock file.
15  * - flock() failed to acquire shared lock on exclusive lock file.
16  * - flock() failed to acquire exclusive lock on exclusive lock file.
17  */
18 
19 #include <errno.h>
20 #include <sys/file.h>
21 #include <stdlib.h>
22 
23 #include "tst_test.h"
24 
25 static struct tcase {
26 	int operation;
27 	char *f_lock;
28 } tcases[] = {
29 	{LOCK_SH, "shared lock"},
30 	{LOCK_EX, "exclusive lock"},
31 };
32 
child(int opt,int should_pass,char * lock)33 static void child(int opt, int should_pass, char *lock)
34 {
35 	int retval, fd1;
36 
37 	fd1 = SAFE_OPEN("testfile", O_RDWR);
38 	retval = flock(fd1, opt);
39 	if (should_pass) {
40 		tst_res(retval == -1 ? TFAIL : TPASS,
41 			" Child acquiring %s got %d", lock, retval);
42 	} else {
43 		tst_res(retval == -1 ? TPASS : TFAIL,
44 			" Child acquiring %s got %d", lock, retval);
45 	}
46 
47 	SAFE_CLOSE(fd1);
48 	exit(0);
49 }
50 
verify_flock(unsigned n)51 static void verify_flock(unsigned n)
52 {
53 	int fd2;
54 	pid_t pid;
55 	struct tcase *tc = &tcases[n];
56 
57 	fd2 = SAFE_OPEN("testfile", O_RDWR);
58 	TEST(flock(fd2, tc->operation));
59 	if (TST_RET != 0) {
60 		tst_res(TFAIL | TTERRNO, "flock() failed to acquire %s",
61 			tc->f_lock);
62 		SAFE_CLOSE(fd2);
63 		return;
64 	}
65 
66 	tst_res(TPASS, "Parent had %s", tc->f_lock);
67 
68 	pid = SAFE_FORK();
69 	if (pid == 0)
70 		child(LOCK_SH | LOCK_NB, tc->operation & LOCK_SH, "shared lock");
71 	else
72 		tst_reap_children();
73 
74 	pid = SAFE_FORK();
75 	if (pid == 0)
76 		child(LOCK_EX | LOCK_NB, 0, "exclusive lock");
77 	else
78 		tst_reap_children();
79 
80 	SAFE_CLOSE(fd2);
81 }
82 
setup(void)83 static void setup(void)
84 {
85 	int fd;
86 
87 	fd = SAFE_OPEN("testfile", O_CREAT | O_TRUNC | O_RDWR, 0644);
88 	SAFE_CLOSE(fd);
89 }
90 
91 static struct tst_test test = {
92 	.tcnt = ARRAY_SIZE(tcases),
93 	.test = verify_flock,
94 	.needs_tmpdir = 1,
95 	.setup = setup,
96 	.forks_child = 1,
97 };
98