1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) Wipro Technologies Ltd, 2002. All Rights Reserved.
4 * Copyright (c) Linux Test Project, 2002-2018
5 * Author: Vatsal Avasthi
6 */
7
8 /*\
9 * [Description]
10 *
11 * Verify flock(2) returns -1 and set proper errno:
12 *
13 * - EBADF if the file descriptor is invalid
14 * - EINVAL if the argument operation does not include LOCK_SH,LOCK_EX,LOCK_UN
15 * - EINVAL if an invalid combination of locking modes is used i.e LOCK_SH with LOCK_EX
16 */
17
18 #include <errno.h>
19 #include <sys/file.h>
20
21 #include "tst_test.h"
22
23 static int badfd = -1;
24 static int fd;
25
26 static struct tcase {
27 int *fd;
28 int operation;
29 int exp_err;
30 } tcases[] = {
31 {&badfd, LOCK_SH, EBADF},
32 {&fd, LOCK_NB, EINVAL},
33 {&fd, LOCK_SH | LOCK_EX, EINVAL},
34 };
35
verify_flock(unsigned n)36 static void verify_flock(unsigned n)
37 {
38 struct tcase *tc = &tcases[n];
39
40 fd = SAFE_OPEN("testfile", O_RDWR);
41 TEST(flock(*tc->fd, tc->operation));
42 if (TST_RET == 0) {
43 tst_res(TFAIL | TTERRNO, "flock() succeeded unexpectedly");
44 SAFE_CLOSE(fd);
45 return;
46 }
47
48 if (tc->exp_err == TST_ERR) {
49 tst_res(TPASS | TTERRNO, "flock() failed expectedly");
50 } else {
51 tst_res(TFAIL | TTERRNO, "flock() failed unexpectedly, "
52 "expected %s", tst_strerrno(tc->exp_err));
53 }
54
55 SAFE_CLOSE(fd);
56 }
57
setup(void)58 static void setup(void)
59 {
60 int fd1;
61
62 fd1 = SAFE_OPEN("testfile", O_CREAT | O_TRUNC | O_RDWR, 0666);
63 SAFE_CLOSE(fd1);
64 }
65
66 static struct tst_test test = {
67 .tcnt = ARRAY_SIZE(tcases),
68 .test = verify_flock,
69 .needs_tmpdir = 1,
70 .setup = setup,
71 };
72