Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <fcntl.h>
- int main(int argc, char *argv[]) {
- if (argc != 4) {
- fprintf(stderr, "Utilizare: %s <fisier> <string-tipar-1> <string-tipar-2>\n", argv[0]);
- exit(-1);
- }
- pid_t pid[3];
- pid[0] = fork();
- int pipe1[2];
- int pipe2[2];
- int pipe3[2];
- if (pipe(pipe1) < 0) {
- fprintf(stderr, "Eroare pipe().\n");
- exit(-1);
- }
- if (pipe(pipe2) < 0) {
- fprintf(stderr, "Eroare pipe().\n");
- exit(-1);
- }
- if (pipe(pipe3) < 0) {
- fprintf(stderr, "Eroare pipe().\n");
- exit(-1);
- }
- if (pid[0] < 0) {
- fprintf(stderr, "Eroare fork() cititor.\n");
- exit(-1);
- }
- if (pid[0] == 0) {
- // cod cititor
- close(pipe1[0]);
- dup2(pipe1[1], 1); // redirectioneaza iesirea standard catre pipe
- close(pipe1[1]);
- close(pipe2[0]);
- close(pipe2[1]);
- close(pipe3[0]);
- close(pipe3[1]);
- execlp("cat", "cat", argv[1], NULL);
- fprintf(stderr, "Eroare execlp().\n");
- exit(-1);
- }
- pid[1] = fork();
- if (pid[1] < 0) {
- fprintf(stderr, "Eroare fork() filtrator-1.\n");
- exit(-1);
- }
- if (pid[1] == 0) {
- // cod filtrator-1
- close(pipe1[1]);
- close(pipe2[0]);
- close(pipe3[0]);
- close(pipe3[1]);
- dup2(pipe1[0], 0);
- dup2(pipe2[1], 1);
- close(pipe1[0]);
- close(pipe2[1]);
- char regex[64];
- int n = sprintf(regex, ".*%s.*", argv[2]);
- regex[n] = '\0';
- execlp("grep", "grep", "-E", regex, NULL);
- fprintf(stderr, "Eroare execlp().\n");
- exit(-1);
- }
- pid[2] = fork();
- if (pid[2] < 0) {
- fprintf(stderr, "Eroare fork() filtrator-2.\n");
- exit(-1);
- }
- if (pid[2] == 0) {
- // cod filtrator-2
- close(pipe1[0]);
- close(pipe1[1]);
- close(pipe2[1]);
- close(pipe3[0]);
- dup2(pipe2[0], 0);
- dup2(pipe3[1], 1);
- close(pipe2[0]);
- close(pipe3[1]);
- char regex[64];
- int n = sprintf(regex, ".*%s.*", argv[3]);
- regex[n] = '\0';
- execlp("grep", "grep", "-E", regex, NULL);
- fprintf(stderr, "Eroare execlp().\n");
- exit(-1);
- }
- // cod parinte
- close(pipe1[0]);
- close(pipe1[1]);
- close(pipe2[0]);
- close(pipe2[1]);
- close(pipe3[1]);
- char buffer[512];
- int r;
- int k = 0;
- while ((r = read(pipe3[0], buffer, sizeof(buffer)))) {
- buffer[r] = '\0';
- for (int i = 0; i < r; i++) {
- if (buffer[i] == '\n') {
- k++;
- }
- }
- }
- close(pipe3[0]);
- fprintf(stdout, "%d\n", k);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement