Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* prog file
- Fiul 1 transmite continutul <file> catre fiul 2, care filtreaza liniile ce contin cel putin o cifra ([0-9]) si le transmite catre fiul 3.
- Al treilea fiu afiseaza numarul de linii.
- Parintele si fiii se executa in paralel!
- Parintele afiseaza ... pana la term tuturor fiilor si afiseaza codurile de retur pe masura ce se termina fiecare fiu.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <string.h>
- int main()
- {
- int pfd1[2];
- int pfd2[2];
- int pfd3[2];
- int status1, status2;
- pid_t pid[2];
- if (pipe(pfd1) < 0)
- {
- perror("eroare pipe 1");
- exit(EXIT_FAILURE);
- }
- if (pipe(pfd2) < 0)
- {
- perror("eroare pipe 2");
- exit(EXIT_FAILURE);
- }
- if (pipe(pfd3) < 0)
- {
- perror("eroare pipe 2");
- exit(EXIT_FAILURE);
- }
- if ((pid[0] = fork()) < 0)
- {
- perror("eroare fork 1");
- exit(EXIT_FAILURE);
- }
- if (pid[0] == 0)
- {
- if ((pid[1] = fork()) < 0)
- {
- perror("eroare fork 2");
- exit(EXIT_FAILURE);
- }
- if (pid[1] == 0) // cod fiu 2
- {
- char block[32];
- int i, r;
- close(pfd2[1]);
- close(pfd1[0]);
- close(pfd1[1]);
- close(pfd3[0]);
- int v[26] = {0};
- while ((r = read(pfd2[0], block, sizeof(block))))
- {
- for (i = 0; i < r; i++)
- v[block[i] - 'a'] ++;
- }
- int fd;
- if ((fd = open("statistica.txt", O_WRONLY | O_TRUNC | O_CREAT, 0666)) == -1)
- {
- perror("eroare statistica");
- exit(EXIT_FAILURE);
- }
- char str[32];
- int k = 0;
- for (i = 0; i < 26; i++)
- {
- if (v[i] > 0)
- {
- sprintf(str, "%c - %d\n", i + 'a', v[i]);
- write(fd, str, strlen(str));
- k ++;
- }
- }
- sprintf(str, "%d litere distincte\n", k);
- write(pfd3[1], str, strlen(str));
- close(fd);
- close(pfd2[0]);
- close(pfd3[1]);
- exit(2);
- }
- else // cod fiu 1
- {
- char block[32];
- int i, r;
- close(pfd1[1]);
- close(pfd2[0]);
- close(pfd3[0]);
- close(pfd3[1]);
- while ((r = read(pfd1[0], block, sizeof(block))))
- {
- for (i = 0; i < r; i++)
- {
- if (block[i] >= 'a' && block[i] <= 'z')
- write(pfd2[1], &block[i], sizeof(char));
- }
- }
- close(pfd2[1]);
- close(pfd1[0]);
- exit(1);
- }
- }
- else // cod parinte
- {
- int fd;
- char block[32];
- if ((fd = open("date.txt", O_RDONLY)) == -1)
- {
- perror("eroare fisier");
- exit(EXIT_FAILURE);
- }
- int r, i;
- close(pfd1[0]);
- close(pfd2[0]);
- close(pfd2[1]);
- close(pfd3[1]);
- while ((r = read(fd, block, sizeof(block))))
- {
- for (i = 0; i < r; i++)
- write(pfd1[1], &block[i], sizeof(char));
- }
- close(pfd1[1]);
- close(fd);
- while ((r = read(pfd3[0], block, sizeof(block))))
- {
- for (i = 0; i < r; i++)
- printf("%c", block[i]);
- }
- close(pfd3[0]);
- wait(&status1);
- wait(&status2);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement