Advertisement
MarioJTurco

Untitled

Jan 21st, 2020
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.27 KB | None | 0 0
  1. #include <errno.h>
  2. #include <fcntl.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <sys/stat.h>
  6. #include <sys/types.h>
  7. #include <sys/wait.h>
  8. #include <unistd.h>
  9. int stop(char *, int);
  10. int main(int argc, char **argv) {
  11.   int pipeAlPadre[2], pipeAlFiglio[2];
  12.   pid_t pid1, pid2;
  13.   int readChar;
  14.   if (argc != 3)
  15.     perror("Insert 2 files"), exit(-1);
  16.   if (pipe(pipeAlPadre) < 0)
  17.     perror("Pipe 1"), exit(-1);
  18.   pipe(pipeAlPadre);
  19.   if ((pid1 = fork()) < 0)
  20.     perror("Fork 1"), exit(-1);
  21.   if (pid1 == 0) { /*figlio 1*/
  22.     int fileDesc;
  23.     char buffer[2];
  24.     char stopSign = '*';
  25.     if ((fileDesc = open(argv[1], O_RDONLY)) < 0)
  26.       perror("File opening 1"), exit(-1);
  27.     close(pipeAlPadre[0]);
  28.     while ((readChar = read(fileDesc, buffer, 2))) {
  29.       if (readChar == 2)
  30.         write(pipeAlPadre[1], buffer, 2);
  31.       else
  32.         write(pipeAlPadre[1], &stopSign, sizeof(char));
  33.     }
  34.     close(pipeAlPadre[1]);
  35.     close(fileDesc);
  36.   } else {
  37.     pipe(pipeAlFiglio);
  38.     if ((pid2 = fork()) < 0)
  39.       perror("Fork 2"), exit(-1);
  40.     if (pid2 == 0) { /* figlio 2*/
  41.       int fileDesc, readChar;
  42.       char buffer[4];
  43.       char bufferOut[2];
  44.       close(pipeAlFiglioa[1]);
  45.       if ((fileDesc = open(argv[2], O_WRONLY | O_CREAT, S_IRWXU | S_IRWXO)) < 0)
  46.         perror("Open 2"), exit(-1);
  47.       while ((readChar = read(pipeAlFiglio[0], buffer, 4))) {
  48.         if (readChar == 4) {
  49.           bufferOut[0] = buffer[0];
  50.           bufferOut[1] = buffer[3];
  51.           write(fileDesc, bufferOut, 2);
  52.         }
  53.       }
  54.       close(pipeAlFiglio[0]);
  55.       close(fileDesc);
  56.     } else { /*padre*/
  57.       char buffer[4];
  58.       int readChar;
  59.  
  60.       close(pipeAlPadre[1]);
  61.       close(pipeAlFiglio[0]);
  62.       while ((readChar = read(pipeAlPadre[0], buffer, 4)) == 4) {
  63.         if (stop(buffer, 4)) {
  64.           break;
  65.         } else {
  66.           if (buffer[0] != buffer[3]) {
  67.             printf("Inviato\n");
  68.             write(pipeAlFiglio[1], buffer, 4);
  69.           }
  70.         }
  71.       }
  72.       close(pipeAlPadre[0]);
  73.       close(pipeAlFiglio[1]);
  74.     }
  75.   }
  76.   return 0;
  77. }
  78.  
  79. int stop(char *String, int dim) {
  80.   char c = '*';
  81.   int index = 0;
  82.   while (index < dim) {
  83.     if (String[index] == c)
  84.       return 1;
  85.     index++;
  86.   }
  87.   return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement