[英]Pipe in C UNIX shell
I am not very sure how to create a pipe between two child processes. 我不太确定如何在两个子进程之间创建管道。 This is the way I did it: 这就是我这样做的方式:
pipe(&fd[0]); //Create a pipe
proc1 = fork();
//Child process 1
if (proc1 == 0)
{
close(fd[0]); //process1 doenst need to read from pipe
close(STD_INPUT); //prepare for output
dup(fd[1]); //Standard output = fd[1]
close(fd[1]);
execvp(parameter[0], parameter); //Execute the process
}
else
{
proc2 = fork();
if (proc2 == 0)
{
close(fd[1]);
close(STD_OUTPUT);
dup(fd[0]);
close(fd[0]);
execvp(parameter2[0], parameter2);
}
//Parent process
else
{
waitpid(-1, &status, 0); //Wait for the child to be done
}
}
I am trying to redirect the output of one child process to another, but I think I am making a mistake with the pipe in the second child process because when I run the program with the 2nd child process I get incorrect results (like a simple execution like "ls" is executed improperly), however, if I remove the second child process, the program runs fine (not including pipe, just simple fork: ls, ls -l, ps, etc.). 我正在尝试将一个子进程的输出重定向到另一个子进程,但我认为我在第二个子进程中使用管道时出错了,因为当我使用第二个子进程运行程序时,我得到的结果不正确(就像一个简单的执行像“ls”执行不当),但是,如果我删除第二个子进程,程序运行正常(不包括管道,只是简单的fork:ls,ls -l,ps等)。
The best answer I can give is Beej's Guide to Unix IPC . 我能给出的最佳答案是Beej的Unix IPC指南 。
(Peek at section 4.3, where he gives a very similar example to the question you asked...) (看看第4.3节,他给出了一个与你问的问题非常相似的例子......)
In the child process 1 setup, close(STD_INPUT); dup(fd[1]);
在子进程1设置中, close(STD_INPUT); dup(fd[1]);
close(STD_INPUT); dup(fd[1]);
will duplicate fd[1]
to the lowest available descriptor, which is 0 ( STD_INPUT
) rather than 1 ( STD_OUTPUT
). 将fd[1]
复制到最低可用描述符,即0( STD_INPUT
)而不是1( STD_OUTPUT
)。 Don't you want to close STD_OUTPUT
instead? 你不想关闭STD_OUTPUT
吗? Also, I'd recommend dup2(fd[1], STD_OUTPUT)
in place of this sequence; 另外,我建议使用dup2(fd[1], STD_OUTPUT)
代替这个序列; it will do what you want and is more clear anyway. 它会做你想做的事情,无论如何都会更清楚。
Likewise child process 2 uses STD_OUTPUT
where you probably want STD_INPUT
. 同样,子进程2使用STD_OUTPUT
,您可能需要STD_INPUT
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.