Add exercice #7 code
[TD_IML.git] / TD1 / part_two / exo.c
diff --git a/TD1/part_two/exo.c b/TD1/part_two/exo.c
new file mode 100644 (file)
index 0000000..0194d04
--- /dev/null
@@ -0,0 +1,58 @@
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+void show_proc_pids() {
+    pid_t current_pid = getpid();
+    pid_t parent_pid = getppid();
+
+    printf("[%d] Mon PID: %d\n", current_pid, current_pid);
+    printf("[%d] PID du parent: %d\n", current_pid, parent_pid);
+}
+
+int main() {
+    int pipefd[2];
+    char buf;
+    printf("Courant:\n");
+    show_proc_pids();
+
+    if (pipe(pipefd) == -1) {
+        printf("Pipe creation erreur\n");
+        exit(EXIT_FAILURE);
+    };
+
+    pid_t cpid = fork();
+
+    if (cpid == -1) {
+        printf("Erreur de clonage\n");
+        exit(EXIT_FAILURE);
+    } else if (cpid == 0) {
+        printf("Fils:\n");
+        show_proc_pids();
+        const char* msg = "Coucou papa !";
+        close(pipefd[0]);
+        write(pipefd[1], msg, strlen(msg));
+        close(pipefd[1]);
+        exit(EXIT_SUCCESS);
+    } else {
+        printf("Parent:\n");
+        show_proc_pids();
+        close(pipefd[1]);
+        
+        while (read(pipefd[0], &buf, 1) > 0) {
+            write(STDOUT_FILENO, &buf, 1);
+        }
+                       
+        write(STDOUT_FILENO, "\n", 1);
+        close(pipefd[0]);
+        wait(NULL);
+        exit(EXIT_SUCCESS);
+    }
+    
+    /* unreachable code */
+    return EXIT_SUCCESS;
+}