在C中创建管道
可能的重复:
C UNIX shell 中的管道
我试图在 2 个子进程之间创建一个管道: Child1 关闭管道的输入和输出 Child2 关闭输出并接受输入:
pipe(&fd[0]); //Create a pipe
proc1 = fork();
//Child process 1
if (proc1 == 0)
{
close(fd[0]); //process1 doenst need to read from pipe
dup2(fd[1], STD_OUTPUT);
close(fd[1]);
execvp(parameter[0], parameter); //Execute the process
}
//Create a second child process
else
{
//Child process 2
proc2 = fork();
if (proc2 == 0)
{
close(fd[1]);
dup2(fd[0], STD_INPUT);
close(fd[0]);
execvp(parameter2[0], parameter2);
}
//Parent process
else
{
waitpid(-1, &status, 0); //Wait for the child to be done
}
}
但是,我在某个地方出错了,我不知道到底在哪里(没有任何错误,更多的是逻辑错误)
Possible Duplicate:
Pipe in C UNIX shell
I was trying to create a pipe between 2 child process:
Child1 closes input and outputs to pipe
Child2 closes output and accepts input:
pipe(&fd[0]); //Create a pipe
proc1 = fork();
//Child process 1
if (proc1 == 0)
{
close(fd[0]); //process1 doenst need to read from pipe
dup2(fd[1], STD_OUTPUT);
close(fd[1]);
execvp(parameter[0], parameter); //Execute the process
}
//Create a second child process
else
{
//Child process 2
proc2 = fork();
if (proc2 == 0)
{
close(fd[1]);
dup2(fd[0], STD_INPUT);
close(fd[0]);
execvp(parameter2[0], parameter2);
}
//Parent process
else
{
waitpid(-1, &status, 0); //Wait for the child to be done
}
}
However, I am going wrong somewhere and I don't know exactly where (there aren't any errors, its more of a logic error)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
管子是向后的。
fd[1]
用于写入,fd[0]
用于读取。旁注:
pipe(&fd[0]);
看起来有点奇怪...pipe(fd);
是等效的,但是(在我看来)更清晰。The pipe is backwards.
fd[1]
is for writing,fd[0]
is for reading.Side note:
pipe(&fd[0]);
looks a little weird...pipe(fd);
is equivalent, but (to my eyes) clearer.