-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2-28lock_set.c
More file actions
48 lines (42 loc) · 947 Bytes
/
2-28lock_set.c
File metadata and controls
48 lines (42 loc) · 947 Bytes
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
/*lock_set.c*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int lock_set(int fd, int type){
struct flock old_lock, lock;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_type = type;
lock.l_pid = -1;
fcntl(fd, F_GETLK, &lock);
if(lock.l_type != F_UNLCK){
if(lock.l_type == F_RDLCK){
printf("Read lock already set by %d\n", lock.l_pid);
}
else if(lock.l_type == F_WRLCK){
printf("Write lock already set by %d\n", lock.l_pid);
}
}
lock.l_type = type;
if((fcntl(fd, F_SETLKW, &lock)) < 0){
printf("Lock failed:type = %d\n", lock.l_type);
return -1;
}
switch(lock.l_type){
case F_RDLCK:
printf("Read lock set by %d\n", getpid());
break;
case F_WRLCK:
printf("Write lock set by %d\n", getpid());
break;
case F_UNLCK:
printf("Release lock by %d\n", getpid());
return 1;
break;
}
return 0;
}