1
votes

I am trying to use execvp to run grep. The thought behind this program is to fork a child process, make the child sort a file named sortfile, then the parent process shall use grep on the sorted output. Below is my code.

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

#define READ 0
#define WRITE 1

int main(int argc, char* argv) {
    pid_t cpid;
    int status;
    int pipefd[2];
    pipe(pipefd);
    char* args[] = {"grep", "f", NULL};

    cpid = fork();
    if(cpid == 0) {
        dup2(pipefd[READ], READ);
        dup2(pipefd[WRITE], WRITE);
        close(pipefd[READ]);
        close(pipefd[WRITE]);

        if(execlp("sort", "sort", "sortfile", NULL) == -1) {
            perror("sort");
        }       
    } else {
        dup2(pipefd[READ], READ);
        dup2(pipefd[WRITE], WRITE);
        close(pipefd[READ]);
        close(pipefd[WRITE]);
        wait(&status);

        if(execvp("grep", args) == -1) {
            perror("grep");
        }

    }
}

I am using dup2 to copy the file descriptors of the pipe to stdin and stdout and then closing unused file descriptors. Even though doing this the program never returns, which leads me to believe it's trying to read from a file descriptor that's not being written to, thus blocking the process. I'm completely lost on this and could use some hints. The content of sortfile is a b f s g.

1
My god, I didn't even think about that. I fixed the dup2 calls and it's working. If you post it as an answer I will accept it. - Simon Carlson

1 Answers

2
votes

The dup2 calls are identical for both parent and child. That can't be right. The child(sort) needs to write to the pipe that the parent(grep) reads from.