Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.62 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/wait.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <stdlib.h>
  7.  
  8. int main(int argc, char* argv[]) {
  9.    
  10.     int pfd1[2];
  11.     pipe(pfd1);
  12.     int pfd2[2];
  13.     pipe(pfd2);
  14.  
  15.     int pid1, pid2;
  16.  
  17.     FILE* out = fdopen(pfd2[1], "w");
  18.     fprintf(out, "%d", 1);
  19.     fflush(out);
  20.     fclose(out);
  21.  
  22.     int n = strtol(argv[1], NULL, 10);
  23.  
  24.     if(!(pid1 = fork())) {
  25.         close(pfd1[0]); close(pfd2[1]);
  26.  
  27.         FILE* in = fdopen(pfd2[0], "r");
  28.         FILE* out = fdopen(pfd1[1], "w");
  29.  
  30.         int y;
  31.         while(fscanf(in, "%d", &y) > 0) {
  32.             if(y >= n)  {
  33.                 break;
  34.             }
  35.             printf("%d %d\n", y, 1);
  36.             fflush(stdout);
  37.             y++;
  38.             fprintf(out, "%d", y);
  39.             fflush(out);
  40.  
  41.         }
  42.  
  43.         close(pfd1[1]);
  44.         close(pfd2[0]);
  45.         fclose(in); fclose(out);
  46.         _exit(0);
  47.  
  48.     }
  49.  
  50.     if(!(pid2 = fork())) {
  51.         close(pfd2[0]); close(pfd1[1]);
  52.  
  53.         FILE* in = fdopen(pfd1[0], "r");
  54.         FILE* out = fdopen(pfd2[1], "w");
  55.  
  56.         int y;
  57.         while(fscanf(in, "%d", &y) > 0) {
  58.             if(y >= n) {
  59.                 break;
  60.             }
  61.             printf("%d %d\n", y, 2);
  62.             fflush(stdout);
  63.             y++;
  64.             fprintf(out, "%d", y);
  65.             fflush(out);
  66.         }
  67.  
  68.         close(pfd2[1]);
  69.         close(pfd1[0]);
  70.         fclose(in); fclose(out);
  71.         _exit(0);
  72.     }
  73.  
  74.     close(pfd1[0]); close(pfd1[1]);
  75.     close(pfd2[0]); close(pfd2[1]);
  76.     wait(0); wait(0);
  77.     printf("Done\n");
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement