Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <errno.h>
- #include <fcntl.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <unistd.h>
- int stop(char *, int);
- int main(int argc, char **argv) {
- int pipeAlPadre[2], pipeAlFiglio[2];
- pid_t pid1, pid2;
- int readChar;
- if (argc != 3)
- perror("Insert 2 files"), exit(-1);
- if (pipe(pipeAlPadre) < 0)
- perror("Pipe 1"), exit(-1);
- pipe(pipeAlPadre);
- if ((pid1 = fork()) < 0)
- perror("Fork 1"), exit(-1);
- if (pid1 == 0) { /*figlio 1*/
- int fileDesc;
- char buffer[2];
- char stopSign = '*';
- if ((fileDesc = open(argv[1], O_RDONLY)) < 0)
- perror("File opening 1"), exit(-1);
- close(pipeAlPadre[0]);
- while ((readChar = read(fileDesc, buffer, 2))) {
- if (readChar == 2)
- write(pipeAlPadre[1], buffer, 2);
- else
- write(pipeAlPadre[1], &stopSign, sizeof(char));
- }
- close(pipeAlPadre[1]);
- close(fileDesc);
- } else {
- pipe(pipeAlFiglio);
- if ((pid2 = fork()) < 0)
- perror("Fork 2"), exit(-1);
- if (pid2 == 0) { /* figlio 2*/
- int fileDesc, readChar;
- char buffer[4];
- char bufferOut[2];
- close(pipeAlFiglioa[1]);
- if ((fileDesc = open(argv[2], O_WRONLY | O_CREAT, S_IRWXU | S_IRWXO)) < 0)
- perror("Open 2"), exit(-1);
- while ((readChar = read(pipeAlFiglio[0], buffer, 4))) {
- if (readChar == 4) {
- bufferOut[0] = buffer[0];
- bufferOut[1] = buffer[3];
- write(fileDesc, bufferOut, 2);
- }
- }
- close(pipeAlFiglio[0]);
- close(fileDesc);
- } else { /*padre*/
- char buffer[4];
- int readChar;
- close(pipeAlPadre[1]);
- close(pipeAlFiglio[0]);
- while ((readChar = read(pipeAlPadre[0], buffer, 4)) == 4) {
- if (stop(buffer, 4)) {
- break;
- } else {
- if (buffer[0] != buffer[3]) {
- printf("Inviato\n");
- write(pipeAlFiglio[1], buffer, 4);
- }
- }
- }
- close(pipeAlPadre[0]);
- close(pipeAlFiglio[1]);
- }
- }
- return 0;
- }
- int stop(char *String, int dim) {
- char c = '*';
- int index = 0;
- while (index < dim) {
- if (String[index] == c)
- return 1;
- index++;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement