Add lockf course code.
[TD_SE.git] / lockf / lockf.c
1 #include <unistd.h>
2 #include <fcntl.h>
3 #include <sys/wait.h>
4
5 int main() {
6 int i, fd = 1;
7
8 if (fork()) //il s'agit du père
9 {
10 lseek(fd, 0, 0);
11 if (lockf(fd, F_LOCK, 1) < 0) {
12 write(fd, "pere lockf failed\n", 18);
13 return -1;
14 }
15 for (i = 0; i < 5; i++) {
16 write(fd, "pere ecrit\n", 12);
17 sleep(1);
18 }
19 write(fd, "pere va liberer le verrou\n", 26);
20 lseek(fd, 0, 0);
21 lockf(fd, F_ULOCK, 0);
22 wait(NULL);
23 } else { //il s'agit du fils
24 lseek(fd, 0, 0); //verrouillé l'octet 0
25 if (lockf(fd, F_LOCK, 1) < 0) {
26 write(fd, "fils lockf failed\n", 18);
27 return -1;
28 }
29 for (i = 0; i < 4; i++) {
30 write(fd, "fils ecrit\n", 12);
31 sleep(1);
32 }
33 write(fd, "fils va liberer le verrou\n", 26);
34 lseek(fd, 0, 0);
35 lockf(fd, F_ULOCK, 0);
36 }
37 close(fd);
38 return 0;
39 }