简体   繁体   English

使用 pipe 执行 cat 和 grep

[英]Using a pipe to execute cat and grep

I want to execute cat on a file then search for the number of times a string is present in this file using grep我想在文件上执行cat然后使用grep搜索该文件中存在的字符串的次数

My current code:我当前的代码:

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

int main() {

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

  if(pid == 0) {
    // close sdout and redirect output to fd[1]
    close(1);
    dup(fd[1]);
    close(fd[0]);
    close(fd[1]);

    char *exp[] = {"cat", "filename.txt", NULL};
    if( (execvp("cat", exp)) < 0) {
      perror("Execvp failed from child");
    }
    exit(EXIT_FAILURE);
  }

  else if(pid > 0) {
    // close stdin and redirect input to fd[0]
    wait(NULL);
    close(0);
    dup(fd[0]);
    close (fd[1]);
    close(fd[0]);

    char *exp[] = {"grep", "-c", "name", "filename.txt", NULL};

    if((execvp("grep", exp)) < 0) {
      perror("Execvp failed from parent");
    }
    exit(EXIT_FAILURE);
  }

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

I am getting an output of 0 which is wrong as the string I am searching for is present in the file and running grep from the terminal results in a different output, ani idea on why this is happening and what do do?我得到一个 0 的 output 这是错误的,因为我正在搜索的字符串存在于文件中并从终端运行grep会导致不同的 output 发生这种情况,为什么要这样做?

Solution:解决方案:

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

int main() {
  pid_t pid ;
  int fd[2];
  pipe(fd);

  pid = fork(); 

  if(pid == 0) {
    // close sdout and redirect output to fd[1]
    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 stdin and redirect input to fd[0]
    close(0);
    dup(fd[0]);
    close (fd[1]);
    close(fd[0]);

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

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

The main fix to the problem was removing the filename from the comments as one user pointed it, this got me a correct output.该问题的主要解决方法是从评论中删除文件名,正如一位用户指出的那样,这让我得到了正确的 output。 However, as another user suggested in the comments there was some optimization to be done such that removing the wait(NULL) and removing testing for what exec returns.但是,正如另一位用户在评论中建议的那样,需要进行一些优化,例如删除wait(NULL)并删除对exec返回的内容的测试。 Thanks everyone!感谢大家!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM