#define _POSIX_C_SOURCE 1 #include #include #include #include #include #include #include "formater.h" static void attendre_les_enfants(void); static void lancer(char *executable, int entree, int sortie); static void perror_and_exit(void); int main(int argc, char *argv[]) { int tube_a_b[2]; int tube_b_a[2]; int pid_a; if (argc != 3) { fprintf(stderr, "Usage: %s commande commande\n", argv[0]); return EXIT_FAILURE; } if (pipe(tube_a_b) == -1 || pipe(tube_b_a) == -1) perror_and_exit(); pid_a = fork(); if (pid_a == -1) perror_and_exit(); if (pid_a > 0) { int pid_b = fork(); if (pid_b == -1) { perror(NULL); kill(pid_a, SIGKILL); return EXIT_FAILURE; } if (pid_b > 0) { close(tube_a_b[0]); close(tube_a_b[1]); close(tube_b_a[0]); close(tube_b_a[1]); attendre_les_enfants(); } else { /* Enfant B */ close(tube_a_b[1]); close(tube_b_a[0]); lancer(argv[2], tube_a_b[0], tube_b_a[1]); } } else { /* Enfant A */ close(tube_a_b[0]); close(tube_b_a[1]); lancer(argv[1], tube_b_a[0], tube_a_b[1]); } return EXIT_SUCCESS; } static void attendre_les_enfants(void) { for (;;) { int pid = wait(NULL); if (pid != -1) { printf("[parent] Terminaison de %d\n", pid); continue; } if (errno == ECHILD) break; } } static void lancer(char *executable, int entree, int sortie) { char *commande = formater(String, executable, String, " ", Int, entree, String, " ", Int, sortie, Eop); printf("Exécution de \"%s\"\n", commande); execlp("sh", "sh", "-c", commande, 0); perror("sh"); exit(EXIT_FAILURE); } static void perror_and_exit(void) { perror(NULL); exit(EXIT_FAILURE); }