Выполнение cat | grep | grep с использованием 2 каналов - PullRequest
0 голосов
/ 09 апреля 2020

Название говорит само за себя о том, что я хочу сделать, вот мой текущий код:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main() {

  pid_t pid ;
  int fd[2], fd2[2];
  pipe(fd);
  pipe(fd2);
  pid = fork(); 

  if(pid == 0) {
    close(1);
    dup(fd[1]);
    close(fd[0]);
    close(fd[1]);

    char *exp[] = {"cat", "filename.txt", NULL};
    execvp("cat", exp);
    exit(EXIT_FAILURE);
  } 
  else if(pid > 0) {
    close(1);
    dup(fd2[1]);
    close(fd2[0]);
    close(fd2[1]);

    char *exp[] = {"grep", "-w", "stringname", NULL};
    execvp(exp[0], exp);

    pid_t pid2=fork();

    close(0);
    dup(fd[0]);
    close (fd[1]);
    close(fd[0]);

  char *exp2[] = {"grep", "-c", "stringname", NULL};
  execvp(exp2[0], exp2);

  exit(EXIT_FAILURE);
  }

  else {
    printf("Error in forking");
    exit(EXIT_FAILURE);
  }
  close(fd[0]);
  close(fd[1]);
  close(fd2[0]);
  close(fd2[1]);
  return 0;
}

В настоящее время программа компилируется, но не выполняется (она застревает где-то при выполнении, и я не получить какой-либо вывод), любая помощь о том, что я делаю неправильно и как я могу это исправить?

1 Ответ

1 голос
/ 09 апреля 2020

В вашем коде есть некоторые проблемы:

  1. execvp(exp[0], exp); после того, как первый grep будет выполнен перед вторым fork(). Это ошибка логики c.
  2. Я не совсем понимаю, как вы работаете с файловыми дескрипторами ваших каналов. Вам следует заменить stdin и stdout соответствующими концами труб и закрыть все остальные концы.

Я переписал ваш код с этими изменениями, используя dup2 , чтобы сделать его чище:

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main()
{
    int pipes[4];

    // Create two pipes
    pipe(pipes);
    pipe(pipes + 2);

    // Execute cat
    if (fork() == 0) {
        // Replace output with write end of first pipe
        dup2(pipes[1], 1);

        // Close all ends of pipes (we already copied it with `dup2`)
        close(pipes[0]);
        close(pipes[1]);
        close(pipes[2]);
        close(pipes[3]);

        char *exp[] = {"cat", "filename.txt", NULL};
        execvp(exp[0], exp);
        perror("cat failed");
        exit(EXIT_FAILURE);
    } else {
        // Execute first grep
        if (fork() == 0) {
            // Replace input with read end of 1st pipe
            dup2(pipes[0], 0);

            // Replace output with write end of 2nd pipe
            dup2(pipes[3], 1);

            // Close all ends of pipes
            close(pipes[0]);
            close(pipes[1]);
            close(pipes[2]);
            close(pipes[3]);

            char *exp[] = {"grep", "-w", "stringname", NULL};
            execvp(exp[0], exp);
            perror("first grep failed");
            exit(EXIT_FAILURE);
        } else {
            // Execute second grep
            if (fork() == 0) {
                // Replace input with read end of 2nd pipe
                dup2(pipes[2], 0);

                // Close all ends of pipes
                close(pipes[0]);
                close(pipes[1]);
                close(pipes[2]);
                close(pipes[3]);

                char *exp[] = {"grep", "-c", "stringname", NULL};
                execvp(exp[0], exp);
                perror("second grep failed");
                exit(EXIT_FAILURE);
            }
        }
    }

    // Close all ends of pipes
    close(pipes[0]);
    close(pipes[1]);
    close(pipes[2]);
    close(pipes[3]);

    for (int i = 0; i < 3; i++) {
        wait(NULL);
    }

    return 0;
}
...