Tyler Sebastian
Tyler Sebastian

Reputation: 9458

Reader of Pipe Doesn't See EOF or EOS

In this function, how do I make it so that the parent stops trying to read from the pipe. I.e. if I run the command ls | grep test grep won't output test and test.c and then wait for user input?

pipe(pipefd);

int pid = fork();
if (pid != 0) {
    dup2(pipefd[0], STDIN_FILENO);
    int rv2 = execv(get_contain_dir(command_to), args_to);
    close(pipefd[0]);
} else {
    dup2(pipefd[1], STDOUT_FILENO);
    int rv1 = execv(get_contain_dir(command_from), args_from);
    close(pipefd[1]);
}

Upvotes: 2

Views: 220

Answers (1)

Giuseppe Pes
Giuseppe Pes

Reputation: 7912

You are not closing the pipes correctly. Each process must close the pipe that it does not use :

int pid = fork();
if (pid != 0) {
    dup2(pipefd[0], STDIN_FILENO);
    close(pipefd[1]); // not using the left side
    int rv2 = execv(get_contain_dir(command_to), args_to);

} else {
    dup2(pipefd[1], STDOUT_FILENO);
    close(pipefd[0]);  // not using the right side 
    int rv1 = execv(get_contain_dir(command_from), args_from);
}

Upvotes: 2

Related Questions