#include #include #include #include /* Ordre des pipes: AB 0 AC 1 AD 2 BI 3 CE 4 CF 5 DH 6 EG 7 FG 8 GI 9 HI 10 IA 11 */ int main() { int* fds[12]; for (int i=0; i < 12; i++) { fds[i] = malloc(sizeof(int)*2); pipe(fds[i]); } int i=0; for (; i < 9; i++) { if (fork()) { break; } // Generate 9 processes if (i == 8) { return 0; } } int input[3] = {-1, -1, -1}; int output[3] = {-1, -1, -1}; char id = 'A'+i; switch (id) { case 'A': {// A input[0] = 11; output[0] = 0; output[1] = 1; output[2] = 2; } break; case 'B': {// B input[0] = 0; output[0] = 3; } break; case 'C': {// C input[0] = 1; output[0] = 4; output[1] = 5; } break; case 'D': {// D input[0] = 2; output[0] = 6; } break; case 'E': {// E input[0] = 4; output[0] = 7; } break; case 'F': {// F input[0] = 5; output[0] = 8; } break; case 'G': {// G input[0] = 7; input[1] = 8; output[0] = 9; } break; case 'H': {// H input[0] = 6; output[0] = 10; } break; case 'I': {// I input[0] = 3; input[1] = 9; input[2] = 10; output[0] = 11; } break; default: return -1; } FILE* in_stream[3]; FILE* out_stream[3]; for (int j=0; j < 3; j++) { if (input[j] != -1) { in_stream[j] = fdopen(fds[input[j]][0], "r"); } if (output[j] != -1) { out_stream[j] = fdopen(fds[output[j]][1], "w"); } } printf("%c: got %d %d %d > %d %d %d\n", id, input[0], input[1], input[2], output[0], output[1], output[2]); sleep(1); if (id == 'I') { int c; while (1) { // Get things from stdin c = getchar(); for (int j=0; j < 3; j++) { if (output[j] != -1) { fputc(c, out_stream[j]); } } } return 0; } while (1) { printf("%c listening...\n", id); int c, d; d = -1; for (int j=0; j < 3; j++) { if (input[j] != -1) { c = fgetc(in_stream[j]); if (d != -1 && c != d) { fprintf(stderr, "%c got two different chars: %c vs %c\n", id, c, d); } d = c; } } printf("%c received %c\n", id, c); for (int j=0; j < 3; j++) { if (output[j] != -1) { printf("%c transmits %c to %d\n", id, c, output[j]); fputc(c, out_stream[j]); } } } for (int j=0; j < 3; j++) { if (input[j] != -1) { fclose(in_stream[j]); } if (output[j] != -1) { fclose(out_stream[j]); } } }