Skip to content

Commit f0e317b

Browse files
committed
use enum for better readability
1 parent 5fbb802 commit f0e317b

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

file-locking/fcntl-locking.c

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -104,9 +104,14 @@ int
104104
main(int argc, char **argv)
105105
{
106106
struct sigaction act;
107-
int i, j, fd, locking = 0;
107+
int i, j, fd;
108108
struct flock fl;
109109
char *progname = argv[0];
110+
enum {
111+
NO_LOCK = 0,
112+
SHARED_FD,
113+
EXCLUSIVE_FD
114+
} locking = NO_LOCK;
110115

111116
act.sa_handler = sigint_handler;
112117
sigemptyset(&act.sa_mask);
@@ -118,11 +123,11 @@ main(int argc, char **argv)
118123
switch (opt) {
119124
case 'l':
120125
(void) printf("Using locking with a shared fd.\n");
121-
locking = 1;
126+
locking = SHARED_FD;
122127
break;
123128
case 'L':
124129
(void) printf("Using locking with private fd's.\n");
125-
locking = 2;
130+
locking = EXCLUSIVE_FD;
126131
break;
127132
default:
128133
usage(progname);
@@ -135,14 +140,14 @@ main(int argc, char **argv)
135140
if (argc != 1)
136141
usage(progname);
137142

138-
if (locking == 0)
143+
if (locking == NO_LOCK)
139144
printf("Not using locking.\n");
140145

141146
/* Create the file. */
142147
char *filename = argv[0];
143148
if ((fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0666)) == -1)
144149
err(1, "open");
145-
if (locking == 2)
150+
if (locking == EXCLUSIVE_FD)
146151
close(fd);
147152

148153
/* extend the file to FILE_LEN bytes */
@@ -160,7 +165,7 @@ main(int argc, char **argv)
160165
continue;
161166

162167
/* child */
163-
if (locking == 2) {
168+
if (locking == EXCLUSIVE_FD) {
164169
if ((fd = open(filename, O_WRONLY, 0666)) == -1)
165170
err(1, "open");
166171
}
@@ -169,7 +174,7 @@ main(int argc, char **argv)
169174
while (1) {
170175
/* Lock only the 2nd half of the file. */
171176
if (j == FILE_LEN / 2) {
172-
if (locking > 0) {
177+
if (locking > NO_LOCK) {
173178
fl.l_type = F_WRLCK;
174179
if (fcntl(fd, F_SETLKW, &fl) == -1)
175180
err(1, "fcntl");
@@ -186,9 +191,9 @@ main(int argc, char **argv)
186191
}
187192
#endif
188193
/*
189-
* NOTE: If locking is set to 1, the file position
190-
* is shared among the NPROC processes so the
191-
* following could happen (timewise):
194+
* NOTE: If locking is set to SHARED_FD, the file
195+
* position is shared among the NPROC processes
196+
* so the following could happen (timewise):
192197
*
193198
* 1) process in the upper half lseek()s to
194199
* offset > FILE_LEN / 2
@@ -213,7 +218,7 @@ main(int argc, char **argv)
213218
*/
214219
if (j == FILE_LEN) {
215220
j = 0;
216-
if (locking > 0) {
221+
if (locking > NO_LOCK) {
217222
fl.l_type = F_UNLCK;
218223
if (fcntl(fd, F_SETLKW, &fl) == -1)
219224
err(1, "fcntl");

0 commit comments

Comments
 (0)