Commit | Line | Data |
---|---|---|
bb3dd291 JB |
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(); | |
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 | } | |
51 | ||
52 | /* unreachable code */ | |
53 | return EXIT_SUCCESS; | |
54 | } |