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);
}
}