430e74c089d001f28eb25490c34b7dc2914b776a
[TD_IML.git] / TD1 / part_two / exo.c
1 #include <sys/types.h>
2 #include <sys/wait.h>
3
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8
9 void show_proc_pids() {
10 pid_t current_pid = getpid();
11 pid_t parent_pid = getppid();
12
13 printf("[%d] Mon PID: %d\n", current_pid, current_pid);
14 printf("[%d] PID du parent: %d\n", current_pid, parent_pid);
15 }
16
17 int main() {
18 int pipefd[2];
19 char buf;
20 printf("Courant:\n");
21 show_proc_pids();
22
23 if (pipe(pipefd) == -1) {
24 printf("Pipe creation erreur\n");
25 exit(EXIT_FAILURE);
26 };
27
28 pid_t cpid = fork();
29
30 if (cpid == -1) {
31 printf("Erreur de clonage\n");
32 exit(EXIT_FAILURE);
33 } else if (cpid == 0) {
34 printf("Fils:\n");
35 show_proc_pids();
36 const char* str_fmt = "[%d] Coucou papa !\n";
37 close(pipefd[0]);
38 write(pipefd[1], str_fmt, strlen(str_fmt));
39 close(pipefd[1]);
40 exit(EXIT_SUCCESS);
41 } else {
42 printf("Parent:\n");
43 show_proc_pids();
44 close(pipefd[1]);
45 read(pipefd[0], &buf, 20*sizeof(buf));
46 printf(&buf, getpid());
47 close(pipefd[0]);
48 wait(NULL);
49 exit(EXIT_SUCCESS);
50 }
51
52 /* unreachable code */
53 return EXIT_SUCCESS;
54 }