Advertisement
Guest User

Untitled

a guest
Nov 17th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.19 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <sys/types.h>
  5. #include <sys/wait.h>
  6.  
  7. void
  8. work(int snum, FILE *in, FILE *out, int max)
  9. {
  10.     int a;
  11.     while (fscanf(in, "%d", &a) == 1) {
  12.         printf("%d %d\n", snum, a);
  13.         fflush(stdout);
  14.         a++;
  15.         if (a > max)
  16.             exit(0);
  17.         fprintf(out, "%d ", a);
  18.         fflush(out);
  19.     }
  20.     exit(0);
  21. }
  22.  
  23. int main(int argc, char *argv[])
  24. {
  25.     int max = atoi(argv[1]);
  26.    
  27.     int p12[2];
  28.     int p21[2];
  29.  
  30.     pipe(p12);
  31.     pipe(p21);
  32.  
  33.     if (!fork()) {
  34.         close(p21[1]);
  35.         close(p12[0]);
  36.         FILE *in1 = fdopen(p21[0], "r");
  37.         FILE *out1 = fdopen(p12[1], "w");
  38.         work(1, in1, out1, max);
  39.     }
  40.     if (!fork()) {
  41.         close(p12[1]);
  42.         close(p21[0]);
  43.         FILE *in2 = fdopen(p12[0], "r");
  44.         FILE *out2 = fdopen(p21[1], "w");
  45.         work(2, in2, out2, max);
  46.     }
  47.     int x = 1;
  48.     FILE *out = fdopen(p21[1], "w");
  49.     fprintf(out, "%d ", x);
  50.     fflush(out);
  51.  
  52.     close(p12[0]);
  53.     close(p12[1]);
  54.     close(p21[0]);
  55.     close(p21[1]);
  56.     wait(NULL);
  57.     wait(NULL);
  58.     printf("Done\n");
  59.     return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement