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