Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <wait.h>
- #include <fcntl.h>
- int
- main(int argc, char **argv)
- {
- int fd_1_to_2[2];
- int fd_2_to_0[2];
- pipe(fd_1_to_2);
- pipe(fd_2_to_0);
- pid_t gen1 = fork();
- if (gen1 < 0) {
- _exit(0);
- } else if (!gen1) {
- pid_t gen2 = fork();
- if (gen2 < 0) {
- _exit(0);
- } else if (!gen2) {
- close(fd_1_to_2[1]);
- close(fd_2_to_0[0]);
- double elm, sum = 0;
- int flg = 0;
- while (read(fd_1_to_2[0], &elm, sizeof(elm)) == sizeof(elm)) {
- sum += elm;
- flg = 1;
- }
- close(fd_1_to_2[0]);
- if (flg) {
- write(fd_2_to_0[1], &sum, sizeof(sum));
- }
- close(fd_2_to_0[1]);
- exit(0);
- } else {
- close(fd_2_to_0[0]);
- close(fd_2_to_0[1]);
- close(fd_1_to_2[0]);
- FILE *fin = fopen(argv[1], "r");
- double elm;
- while (fscanf(fin, "%lf", &elm) == 1) {
- if (elm >= 0) {
- write(fd_1_to_2[1], &elm, sizeof(elm));
- }
- }
- fclose(fin);
- close(fd_1_to_2[1]);
- wait(NULL);
- exit(0);
- }
- } else {
- close(fd_1_to_2[0]);
- close(fd_1_to_2[1]);
- close(fd_2_to_0[1]);
- wait(NULL);
- double sum;
- if (read(fd_2_to_0[0], &sum, sizeof(sum)) == sizeof(sum)) {
- printf("%.10g\n", sum);
- fflush(stdout);
- }
- close(fd_2_to_0[0]);
- exit(0);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement