我对此问题有一个跟进问题:Classic C. Using pipes in execvp function, stdin and stdout redirection
我需要做同样的事情,但是有两个以上的命令。
如果我执行ls | head | wc
它不起作用。
我的方法是,第一个和最后一个之间的所有命令都需要从管道输入并将其输出到管道。 我的代码如下所示:
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);
}
}