Add lockf course code.
[TD_SE.git] / lockf / lockf.c
diff --git a/lockf/lockf.c b/lockf/lockf.c
new file mode 100644 (file)
index 0000000..f684b17
--- /dev/null
@@ -0,0 +1,39 @@
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/wait.h>
+
+int main() {
+    int i, fd = 1;
+
+    if (fork()) //il s'agit du père
+    {
+        lseek(fd, 0, 0);
+        if (lockf(fd, F_LOCK, 1) < 0) {
+            write(fd, "pere lockf failed\n", 18);
+            return -1;
+        }
+        for (i = 0; i < 5; i++) {
+            write(fd, "pere ecrit\n", 12);
+            sleep(1);
+        }
+        write(fd, "pere va liberer le verrou\n", 26);
+        lseek(fd, 0, 0);
+        lockf(fd, F_ULOCK, 0);
+        wait(NULL);
+    } else { //il s'agit du fils
+        lseek(fd, 0, 0); //verrouillĂ© l'octet 0
+        if (lockf(fd, F_LOCK, 1) < 0) {
+            write(fd, "fils lockf failed\n", 18);
+            return -1;
+        }
+        for (i = 0; i < 4; i++) {
+            write(fd, "fils ecrit\n", 12);
+            sleep(1);
+        }
+        write(fd, "fils va liberer le verrou\n", 26);
+        lseek(fd, 0, 0);
+        lockf(fd, F_ULOCK, 0);
+    }
+    close(fd);
+    return 0;
+}