/* * Programme demandant l'entrée d'un nombre et calculant la fonction * f(x) = 2*x + 1 * Le programme s'arrête une fois qu'on a tapé -1 */ #include #include #include #include #include /* Definition des tubes de communication */ int p_a1[2]; int a1_a2[2]; int a2_p[2]; void *a1(){ int x; int resultat; do { read(p_a1[0], &x, sizeof(x)); if (x != -1) { resultat = 2*x; } else { resultat = x; } write(a1_a2[1], &resultat, sizeof(resultat)); }while(x != -1); pthread_exit(0); } void *a2(){ int resultat; int nouveauResultat; do { read(a1_a2[0], &resultat, sizeof(resultat)); if (resultat != -1) { nouveauResultat = resultat + 1; write(a2_p[1], &nouveauResultat, sizeof(nouveauResultat)); } } while (resultat != -1); pthread_exit(0); } void parent(){ int x, reponse; do { printf("Entrez un entier (ou -1 pour arreter le programme)\n"); scanf("%d", &x); write(p_a1[1], &x, sizeof(x)); if (x != -1){ read(a2_p[0], &reponse, sizeof(reponse)); printf("f(%d) = %d\n\n", x, reponse); } } while (x != -1); } int main(){ pthread_t thA1, thA2; /* Initialisations des tubes */ if (pipe(p_a1)<0) { perror("pipe"); exit(1); } if (pipe(a1_a2)<0) { perror("pipe"); exit(1); } if (pipe(a2_p)<0) { perror("pipe"); exit(1); } /* Fork des enfants */ if (pthread_create(&thA1, NULL, a1, NULL) != 0){ perror("pthread_create"); exit(1); } if (pthread_create(&thA2, NULL, a2, NULL) != 0){ perror("pthread_create"); exit(1); } /* Traitement du parent */ parent(); /* Attente que les threads aient termine pour fermer tous les descripteurs */ if (pthread_join(thA1, NULL) != 0){ perror("pthread_join A1"); exit(1); } if (pthread_join(thA2, NULL) != 0){ perror("pthread_join A2"); exit(1); } close(p_a1[1]); close(a1_a2[0]); close(a2_p[0]); close(a2_p[1]); close(p_a1[0]); close(a1_a2[1]); return 0; }