#define _POSIX_C_SOURCE 1 #include #include #include #include #define TAILLE_TAMPON PIPE_BUF static void parent(int tube); static void enfant(int tube); static void perror_and_exit(void); int main(void) { int tube[2]; int pid; if (pipe(tube) == -1 || (pid = fork()) == -1) perror_and_exit(); if (pid > 0) { close(tube[0]); parent(tube[1]); } else { close(tube[1]); enfant(tube[0]); } printf("[%d] : terminaison\n", getpid()); return EXIT_SUCCESS; } static void parent(int fd) { FILE *flot = fdopen(fd, "w"); if (flot == NULL) perror_and_exit(); fprintf(flot, "Émetteur : %d\n", getpid()); fprintf(flot, "Message : " "À quelle heure vous faites les « en dro » ?\n"); fclose(flot); sleep(5); } static void enfant(int fd) { printf("<< [enfant-%d] Début de réception.\n", getpid()); for (;;) { char tampon[TAILLE_TAMPON]; int n = read(fd, tampon, TAILLE_TAMPON); if (n == -1) perror_and_exit(); if (n == 0) break; write(STDOUT_FILENO, tampon, n); } printf(">> [enfant-%d] Fin de réception.\n", getpid()); } static void perror_and_exit(void) { perror(NULL); exit(EXIT_FAILURE); }