0

I have a follow-up question to this one: Classic C. Using pipes in execvp function, stdin and stdout redirection

I need to do the same, but with more than two commands. If I execute ls | head | wc it doesnt work.

My approach is, that all the commands between the first and the last one need to get input from the pipe and output it to the pipe. My code looks like this:

if(i != 0 && i < notoken - 1) {
            close(STDOUT_FILENO);  //closing stdout
            dup(pipefd[1]);         //replacing stdout with pipe write 
            close(STDIN_FILENO);   //closing stdin
            dup(pipefd[0]);         //replacing stdin with pipe read
            close(pipefd[0]);       //closing pipe read
            close(pipefd[1]);

            argv[0] = token[i];
            argv[1] = NULL;
            execvp(argv[0], argv);
            perror("failed");
            exit(1);
    } else if(i == 0 && notoken > 1) {
        if(fork() == 0) {          //first fork
            close(STDOUT_FILENO);  //closing stdout
            dup(pipefd[1]);         //replacing stdout with pipe write 
            close(pipefd[0]);       //closing pipe read
            close(pipefd[1]);

            argv[0] = token[i];
            argv[1] = NULL;
            execvp(argv[0], argv);
            perror("failed");
            exit(1);
        }
    } else {
        if(fork() ==0) {
            close(STDIN_FILENO);   //closing stdin
            dup(pipefd[0]);         //replacing stdin with pipe read
            close(pipefd[1]);       //closing pipe write
            close(pipefd[0]);

            argv[0] = token[i];
            argv[1] = NULL;
            execvp(argv[0], argv);
            perror("failed");
            exit(1);
        }
    }
manuelgr
  • 498
  • 1
  • 8
  • 26
  • 2
    As a general rule, you need a separate pipe between each pair of processes that want to communicate. It looks like you're trying to use the same one for each pair. – John Bollinger Oct 12 '17 at 19:31
  • 1
    Additionally, your middle process needs to associate both its standard input and its standard output with (different) pipes, but right now it's doing only one. – John Bollinger Oct 12 '17 at 19:34
  • 3
    And for goodness and sanity's sake, use `dup2()` instead of `dup()`! – John Bollinger Oct 12 '17 at 19:34
  • Thanks for the feedback! Would this be right for the "middle" commands with redirected stdin and stdout (SEE ANSWER). – manuelgr Oct 12 '17 at 23:28

0 Answers0