Respect the asked string format for stdout message passing between
[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 const char* str_fmt = "[%d] Coucou papa !\n";
29 pid_t cpid = fork();
30
31 if (cpid == -1) {
32 printf("Erreur de clonage\n");
33 exit(EXIT_FAILURE);
34 } else if (cpid == 0) {
35 printf("Fils:\n");
36 show_proc_pids();
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, strlen(str_fmt));
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 }