我正在学习使用C语言进行Linux系统调用。我完全不了解dup2
的用法。到目前为止,我为2个命令做了dup2
并且它工作正常,但我想不出用3个命令做的方法。
例如,如果我想执行三个命令:
./program1
./program2
./program3
假设这三个程序取决于用户输入。如何使用fork()
和dup2()
管道这些程序的输出?
我只做了2个命令就像魅力一样:
pid2=fork();
if(pid2==0)
{
close(pipe1[0]);
dup2(pipe1[1], STDOUT_FILENO);
close(pipe1[1]);
execvp("./addone",argp);
}
else
{
wait(NULL);
close(pipe1[1]);
dup2(pipe1[0], STDIN_FILENO);
close(pipe1[0]);
execvp("./addone",argp);
}
答案 0 :(得分:0)
首先,你想要放弃if-nesting,否则在管道中有更多进程就会变得无法读取。
对于模拟以下bash行为./addone | ./addone | ./addone
的3个进程,您可能希望编写如下内容:
#include <unistd.h> // dup2(), pipe(), fork(), execvp()
#include <sys/wait.h> // waitpid()
int main() {
int pipe1[2], pipe2[2];
int pid0, pid1, pid2;
char *argp = {"./addone", "first_argument", "second_argument", NULL};
pipe(pipe1);
pid0 = fork();
if (pid0 == 0) {
// close the read end of pipe1:
close(pipe1[0]);
// redirect stdout to the write end of pipe1:
dup2(pipe1[1], 1);
execvp("./addone", argp);
}
pipe(pipe2);
pid1 = fork();
if (pid1 == 0) {
// close the write end of pipe1:
close(pipe1[1]);
// close the read end of pipe2:
close(pipe2[0]);
// redirect stdin to the read end of pipe1:
dup2(pipe1[0], 0);
// redirect stdout to the write end of pipe2:
dup2(pipe2[1], 1);
execvp("./addone", argp);
}
pid2 = fork();
if (pid2 == 0) {
// close unused pipe1:
close(pipe1[0]);
close(pipe1[1]);
// close the write end of pipe2:
close(pipe2[1]);
// redirect stdin to the read end of pipe2:
dup2(pipe2[0], 0);
execvp("./addone", argp);
}
waitpid(pid0, NULL, 0);
waitpid(pid1, NULL, 0);
waitpid(pid2, NULL, 0);
}