-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlock3.c
More file actions
48 lines (39 loc) · 1.03 KB
/
lock3.c
File metadata and controls
48 lines (39 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
const char *test_file = "/tmp/test.lock";
int main()
{
int file_desc;
int byte_count;
char *byte_to_write = "A";
struct flock region_1;
struct flock region_2;
int res;
file_desc=open(test_file,O_RDWR| O_CREAT,0666);
if (!file_desc) {
fprintf(stderr,"Unable to open %s for read/write\n", test_file);
exit(EXIT_FAILURE);
}
for(byte_count=0; byte_count <100;byte_count++){
(void)write(file_desc,byte_to_write,1);
}
region_1.l_type=F_RDLCK;
region_1.l_whence=SEEK_SET;
region_1.l_start=10;
region_1.l_len=20;
region_2.l_type=F_WRLCK;
region_2.l_whence=SEEK_SET;
region_2.l_start=40;
region_2.l_len=10;
printf("Process %d locking file\n",getpid());
res=fcntl(file_desc,F_SETLK,®ion_1);
if(res==-1) fprintf(stderr,"Failed to lock region 1\n");
res=fcntl(file_desc,F_SETLK,®ion_2);
if(res==-1) fprintf(stderr, "Failed to lock region 2\n");
sleep(60);
printf("Process %d closing file\n",getpid());
close(file_desc);
exit(EXIT_SUCCESS);
}