简体   繁体   中英

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

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?

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. 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. Thanks everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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