假设我想编写一个 C 程序来执行与以下命令相同的命令:ls -l | wc -l
以下是一次尝试:
int main(){
int fd;
char *buffer[] = {"ls", "-l", (char *) NULL};
char *buffer1[] = {"wc", "-l",(char *) NULL};
if(fork() == 0){
// I make the STDOUT_FILENO and fd equivalent
if((fd = dup(STDOUT_FILENO)) == -1){
perror("error");
exit(EXIT_FAILURE);
}
close(fd);
if(fork() == 0)
execvp(buffer[0], buffer);
// then I make fd and STDIN_FILENO equivalent in order to put the output of the previous command
// as the input of the second command
if(dup2(fd, STDIN_FILENO) == -1){
perror("error");
exit(EXIT_FAILURE);
}
execvp(buffer1[0], buffer1);
}
exit(EXIT_SUCCESS);
}
但它只是运行ls -l
而不将其输出提供给wc -l