How can I get grep to run and accept input from a pipe?

82 Views Asked by At

My assignment is to run a child process that gets its input from the parent via a pipe. However, when I run the program, I just keep getting the message about proper use of grep:

Usage: grep [OPTION] ... PATTERN [FILE] ...
Try 'grep --help' for more information.

(this is written in C, in case that wasn't clear) Here is the relevant code (error checking/handling not included, for readability):

int main(int argc, char ** argv) {
    char *file = argv[1];
    char *str = argv[2];
    FILE *fp = fopen(file, "r");
    int grep_stat = 0;
    int pipe_grep[2];
    char word[50];
    pipe(pipe_grep);
    //fork grep process
    if (fork() == 0) {
        //GREP CHILD
        dup2(pipe_grep[0],STDIN_FILENO); //now at std in,0
        close(pipe_grep[1]); //close unused end of pipe
        close(pipe_grep[0]); //shared descriptor now closed
        //parent will pass file contents from pipe to search for string. 
        //should check input from stdin, the pipe
        char *args[] = {"grep", str,NULL};
        //grep_stat =
        execvp("grep", args);
    }
    else {
        //PARENT PROCESS
        close(pipe_grep[0]); //close unused side of pipe
        while (fgets(word,50,fp) != NULL) {
            write(pipe_grep[1], word, strlen(word));
            }

I have tried various arrangements of the order in which pipes are closed, and originally I was actually doing this in the child process:

if(fork==()){
    close(pipe_grep[1]); //close unused end of pipe
    close(0); //close stdin
    dup(pipe_grep[0]); //takes lowest available descriptor, 0
    close(pipe_grep[0]); //close shared descriptor
    
}

But that gave me the same error. I don't know if the issue is the pipes or how I'm using execvp, but I'd appreciate someone else looking at it, you'll probably see something I couldn't.

Edit: I am just overworked at the moment. My mistake was running it without all the needed args. Thanks to the people who commented to help me arrive at that solution.

0

There are 0 best solutions below