IML TD(take2):
[TD_IML.git] / TD1 / part_two / exo.c
CommitLineData
bb3dd291
JB
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4#include <unistd.h>
5
39734cca
JB
6#include <sys/types.h>
7#include <sys/wait.h>
8
bb3dd291
JB
9void 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
17int 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();
c2f07545 36 const char* str_fmt = "[%d] Coucou papa !\n";
bb3dd291 37 close(pipefd[0]);
8253f7ac 38 write(pipefd[1], str_fmt, strlen(str_fmt));
bb3dd291
JB
39 close(pipefd[1]);
40 exit(EXIT_SUCCESS);
41 } else {
42 printf("Parent:\n");
43 show_proc_pids();
44 close(pipefd[1]);
c2f07545 45 read(pipefd[0], &buf, 20*sizeof(buf));
8253f7ac 46 printf(&buf, getpid());
bb3dd291
JB
47 close(pipefd[0]);
48 wait(NULL);
49 exit(EXIT_SUCCESS);
50 }
39734cca 51
bb3dd291
JB
52 /* unreachable code */
53 return EXIT_SUCCESS;
54}