74
74
#include <string.h>
75
75
#include <sys/wait.h>
76
76
#include <assert.h>
77
+ #include <stdbool.h>
77
78
78
79
#define FILE_LEN 70
79
80
/* if you change this you MUST change the 'c' array below */
@@ -100,6 +101,67 @@ usage(char *progname)
100
101
errx (1 , "usage: %s [-l|-L] <filename>" , progname );
101
102
}
102
103
104
+ static void
105
+ lock (int fd , struct flock * fl )
106
+ {
107
+ fl -> l_type = F_WRLCK ;
108
+ if (fcntl (fd , F_SETLKW , fl ) == -1 )
109
+ err (1 , "fcntl" );
110
+ }
111
+
112
+ static void
113
+ unlock (int fd , struct flock * fl )
114
+ {
115
+ fl -> l_type = F_UNLCK ;
116
+ if (fcntl (fd , F_SETLKW , fl ) == -1 )
117
+ err (1 , "fcntl" );
118
+ }
119
+
120
+ static void
121
+ dump_file (char * filename , bool locking )
122
+ {
123
+ struct flock fl ;
124
+ char buf [FILE_LEN ];
125
+ ssize_t n ;
126
+ int fd ;
127
+
128
+ if ((fd = open (filename , O_RDONLY )) == -1 )
129
+ err (1 , "open" );
130
+
131
+ /* Set the structure. */
132
+ fl .l_whence = SEEK_SET ;
133
+ fl .l_start = FILE_LEN / 2 ;
134
+ fl .l_len = FILE_LEN / 2 ;
135
+
136
+ while (1 ) {
137
+ /* Lock only the 2nd half of the file. */
138
+ if (locking ) {
139
+ fl .l_type = F_RDLCK ;
140
+ if (fcntl (fd , F_SETLKW , & fl ) == -1 )
141
+ err (1 , "fcntl" );
142
+ }
143
+
144
+ (void ) lseek (fd , SEEK_SET , 0 );
145
+ memset (buf , 0 , sizeof (buf ));
146
+ n = read (fd , buf , sizeof (buf ));
147
+ (void ) write (1 , buf , sizeof (buf ));
148
+ (void ) printf (" %zd\n" , n );
149
+
150
+ sleep (1 );
151
+ if (locking ) {
152
+ fl .l_type = F_UNLCK ;
153
+ if (fcntl (fd , F_SETLKW , & fl ) == -1 )
154
+ err (1 , "fcntl" );
155
+ }
156
+
157
+ /* Let the writers do their job. */
158
+ sleep (1 );
159
+ }
160
+
161
+ /* not reached */
162
+ close (fd );
163
+ }
164
+
103
165
int
104
166
main (int argc , char * * argv )
105
167
{
@@ -174,11 +236,9 @@ main(int argc, char **argv)
174
236
while (1 ) {
175
237
/* Lock only the 2nd half of the file. */
176
238
if (j == FILE_LEN / 2 ) {
177
- if (locking > NO_LOCK ) {
178
- fl .l_type = F_WRLCK ;
179
- if (fcntl (fd , F_SETLKW , & fl ) == -1 )
180
- err (1 , "fcntl" );
181
- }
239
+ if (locking > NO_LOCK )
240
+ lock (fd , & fl );
241
+
182
242
/* Mark the 2nd half of the file. */
183
243
(void ) lseek (fd , j ++ , SEEK_SET );
184
244
(void ) write (fd , "|" , 1 );
@@ -218,16 +278,13 @@ main(int argc, char **argv)
218
278
*/
219
279
if (j == FILE_LEN ) {
220
280
j = 0 ;
221
- if (locking > NO_LOCK ) {
222
- fl .l_type = F_UNLCK ;
223
- if (fcntl (fd , F_SETLKW , & fl ) == -1 )
224
- err (1 , "fcntl" );
225
- }
281
+ if (locking > NO_LOCK )
282
+ unlock (fd , & fl );
226
283
}
227
284
}
228
285
}
229
286
230
- /* Not reached. */
287
+ dump_file ( filename , locking > NO_LOCK );
231
288
for (i = 0 ; i < NPROC ; ++ i )
232
289
(void ) wait (NULL );
233
290
}
0 commit comments