//Michal Lenort //Jakub Gil #include #include #include #include #include int calculate_factorial(int n) { if (n == 0) { return 1; } else { return n * calculate_factorial(n - 1); } } int main(int argc, char *argv[]) { int i =0; if (argc != 2) { printf("Podaj liczbe procesow potomnych jako argument!\n"); return 1; } int n = atoi(argv[1]); // Liczba procesow potomnych int pipe_send[2]; // wysylanie int pipe_receive[2]; // odbieranie if (pipe(pipe_send) == -1 || pipe(pipe_receive) == -1) { perror("Blad podczas tworzenia potoków!"); return 1; } pid_t pid; for (i = 0; i < n; i++) { pid = fork(); if (pid == -1) { perror("Blad podczas tworzenia procesu potomnego!"); return 1; } else if (pid == 0) { // proces potomny close(pipe_send[1]); // Zamykamy koncowkw zapisu potoku wysylajacego int number; while (read(pipe_send[0], &number, sizeof(int)) > 0) { int factorial = calculate_factorial(number); write(pipe_receive[1], &factorial, sizeof(int)); } close(pipe_send[0]); close(pipe_receive[1]); return 0; } } // proces rodzica close(pipe_send[0]); close(pipe_receive[1]); int sum = 0; for (i = 1; i <= n; i++) { write(pipe_send[1], &i, sizeof(int)); } //close close(pipe_send[1]); int factorial; while (read(pipe_receive[0], &factorial, sizeof(int)) > 0) { sum += factorial; } //close close(pipe_receive[0]); printf("Suma obliczonych silni: %d\n", sum); for (i = 0; i < n; i++) { kill(0, SIGTERM); } for (i = 0; i < n; i++) { wait(NULL); } return 0; }