1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) Linux Test Project, 2001-2023
4 * Copyright (c) International Business Machines Corp., 2001
5 */
6
7 /*\
8 * [Description]
9 *
10 * Program for testing file locking. The original data file consists of
11 * characters from 'A' to 'Z'. The data file after running this program
12 * would consist of lines with 1's in even lines and 0's in odd lines.
13 *
14 * Used in nfslock01.sh.
15 */
16
17 #include "nfs_flock.h"
18 #include <errno.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22
main(int argc,char ** argv)23 int main(int argc, char **argv)
24 {
25 int i, fd, mac, nchars, nlines;
26 int offset = 0;
27 char buf[BUFSIZ];
28
29 if (argc != 5) {
30 fprintf(stderr, "Usage: %s <mac num> <file name> <nchars> <nlines>\n",
31 argv[0]);
32 exit(2);
33 }
34
35 fd = open(argv[2], O_RDWR);
36 if (fd < 0) {
37 perror("opening a file");
38 exit(1);
39 }
40
41 mac = atoi(argv[1]);
42 nchars = atoi(argv[3]);
43 nlines = atoi(argv[4]);
44
45 if (nchars > BUFSIZ) {
46 fprintf(stderr, "Exceeded the maximum limit of the buffer (%d)\n", BUFSIZ);
47 exit(3);
48 }
49
50 if (nchars < 1) {
51 fprintf(stderr, "<char/line> must be > 0\n");
52 exit(3);
53 }
54
55 if (nlines < 1) {
56 fprintf(stderr, "<lines> must be > 0\n");
57 exit(3);
58 }
59
60 /*
61 * Replace a line of characters by 1's if it is process one
62 * else with 0's. Number of charcters in any line are nchars-1,
63 * the last character being a newline character.
64 */
65 for (i = 0; i < nchars - 1; i++) {
66 if (mac == 1)
67 buf[i] = '1';
68 else
69 buf[i] = '0';
70 }
71 buf[nchars - 1] = '\n';
72
73 for (i = 0; i < nlines; i++) {
74 if (mac == 1) { /* Set the offset to even lines */
75 if ((i % 2) == 0) {
76 if (i == 0)
77 offset = 0;
78 else
79 offset += 2 * nchars;
80 } else
81 continue;
82 } else { /* Set the offset to odd lines */
83 if ((i % 2) == 1) {
84 if (i == 1)
85 offset = nchars;
86 else
87 offset += 2 * nchars;
88 } else
89 continue;
90 }
91
92 if (writeb_lock(fd, offset, SEEK_SET, nchars) < 0) {
93 fprintf(stderr, "failed in writeb_lock, errno = %d\n", errno);
94 exit(1);
95 }
96
97 lseek(fd, offset, SEEK_SET);
98
99 if (write(fd, buf, nchars) < 0) {
100 fprintf(stderr, "failed to write buffer to test file, errno = %d\n", errno);
101 exit(1);
102 }
103
104 if (unb_lock(fd, offset, SEEK_SET, nchars) < 0) {
105 fprintf(stderr, "failed in unb_lock, errno = %d\n", errno);
106 exit(1);
107 }
108 }
109 exit(0);
110 }
111