Advertisement
elfokd

Untitled

Dec 15th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.69 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <wait.h>
  5. #include <fcntl.h>
  6.  
  7. int
  8. main(int argc, char **argv)
  9. {
  10.     int fd_1_to_2[2];
  11.     int fd_2_to_0[2];
  12.     pipe(fd_1_to_2);
  13.     pipe(fd_2_to_0);
  14.  
  15.     pid_t gen1 = fork();
  16.     if (gen1 < 0) {
  17.         _exit(0);
  18.     } else if (!gen1) {
  19.         pid_t gen2 = fork();
  20.         if (gen2 < 0) {
  21.             _exit(0);
  22.         } else if (!gen2) {
  23.             close(fd_1_to_2[1]);
  24.             close(fd_2_to_0[0]);
  25.             double elm, sum = 0;
  26.             int flg = 0;
  27.             while (read(fd_1_to_2[0], &elm, sizeof(elm)) == sizeof(elm)) {
  28.                 sum += elm;
  29.                 flg = 1;
  30.             }
  31.             close(fd_1_to_2[0]);
  32.             if (flg) {
  33.                 write(fd_2_to_0[1], &sum, sizeof(sum));
  34.             }
  35.             close(fd_2_to_0[1]);
  36.             exit(0);
  37.         } else {
  38.             close(fd_2_to_0[0]);
  39.             close(fd_2_to_0[1]);
  40.             close(fd_1_to_2[0]);
  41.             FILE *fin = fopen(argv[1], "r");
  42.             double elm;
  43.             while (fscanf(fin, "%lf", &elm) == 1) {
  44.                 if (elm >= 0) {
  45.                     write(fd_1_to_2[1], &elm, sizeof(elm));
  46.                 }
  47.             }
  48.             fclose(fin);
  49.             close(fd_1_to_2[1]);
  50.             wait(NULL);
  51.             exit(0);
  52.         }
  53.     } else {
  54.         close(fd_1_to_2[0]);
  55.         close(fd_1_to_2[1]);
  56.         close(fd_2_to_0[1]);
  57.         wait(NULL);
  58.         double sum;
  59.         if (read(fd_2_to_0[0], &sum, sizeof(sum)) == sizeof(sum)) {
  60.             printf("%.10g\n", sum);
  61.             fflush(stdout);
  62.         }
  63.         close(fd_2_to_0[0]);
  64.         exit(0);
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement