我了解管道要运行的命令,如ls -l | wc -l:输入重定向和管道
int pipes[2];
pipe(pipes);
if (fork() == 0){ //first fork
dup2(pipes[1],1);
close(pipes[0]);
close(pipes[1]);
execvp(arr1[0], arr1); //arr1[0] = "ls" and arr1[1] = "-l" and arr1[2] = 0
perror("Ex failed");
exit(1);
}
if (fork() == 0){ //2nd fork
close(pipes[1]);
dup2(pipes[0],0);
close(pipes[0]);
execvp(arr2[0], arr2); //arr2[0] = "wc" and arr2[1] = "-l" and arr2[2] = 0
perror("Ex failed");
exit(1);
}
但是,如何包含输入和输出重定向?可以说我想猫< foo.txt | wc -l
我知道第一个fork需要修改,但我不明白需要什么(另一个dup2()?)。我将不胜感激一些帮助。
谢谢。
你希望用'dup2(pipes [1],[1])完成什么?这是无效的语法;我认为你的意思是'dup2(管道[1],STDOUT_FILENO);'? –
这是一个错字。我会解决它。 – user5832523