管道的哪一端用于输入,哪一端用于输出?
最近我开始怀疑我错误地使用了管道的末端:
从手册页:
pipe() 创建一个管道.. ..pipefd[0] 指的是管道的读取端 管道。 pipelinefd[1]指的是管道的写端。
所以在我看来,我是这样的:
.---------------------------.
/ /\
| pipedfd[0] pipedfd[1]| |
process1 ---> | | -----> process2
| input output| |
\____________________________\/
但是,我在这里的代码和工作表明不然:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
int pipedfd[2];
char buf[30];
pipe(pipedfd);
printf("writing to file descriptor #%d\n", pipedfd[1]);
write(pipedfd[1], "test", 5);
printf("reading from file descriptor #%d\n", pipedfd[0]);
read(pipedfd[0], buf, 5);
printf("read \"%s\"\n", buf);
return 0;
}
即它写入管道的输出(?)并从管道的输入(?)读取?
Recently I started suspecting that I use the ends of the pipes wrongly:
From the man pages:
pipe() creates a pipe.. ..pipefd[0] refers to the read end of the
pipe. pipefd[1] refers to the write end of the pipe.
So in my mind I had it like this:
.---------------------------.
/ /\
| pipedfd[0] pipedfd[1]| |
process1 ---> | | -----> process2
| input output| |
\____________________________\/
However the code that I have here and works suggests otherwise:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
int pipedfd[2];
char buf[30];
pipe(pipedfd);
printf("writing to file descriptor #%d\n", pipedfd[1]);
write(pipedfd[1], "test", 5);
printf("reading from file descriptor #%d\n", pipedfd[0]);
read(pipedfd[0], buf, 5);
printf("read \"%s\"\n", buf);
return 0;
}
Namely it writes to the output(?) of the pipe and reads from the input(?) of the pipe?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简而言之,交换图表中的数字
0
和1
,您就得到了我将在下面描述的内容。来自 Mac OS X 手册页:
我将描述它的常用方式,这可能会澄清它。想象一下,您有一个进程并想要生成一个子进程,您想要向其发送命令。
pipe
并获取两个文件描述符。fork
来创建子进程。fd[1]
) 并保持读取打开。fd[0]
) 文件描述符并保留写入 文件描述符打开。fd[1]
),而子级可以读取另一部分 (fd[0]
)。关闭不是必需的,但通常会完成。如果您需要双向通信,您要么需要第二组文件描述符以及第二次对管道的调用,要么使用双向通道,例如 Unix 域套接字或命名管道。
In a nutshell, swap the numbers
0
and1
in your diagram and you got what I'll describe below.From the Mac OS X man page:
I'll describe how it's often used, that might clear it up. Imagine you have a process and want to spawn a child, to which you want to send commands.
pipe
and get the two file descriptors.fork
to create the child.fd[1]
) and leave the reading one open.fd[0]
) file descriptor and leave the writing one open.fd[1]
) and the child can read on the other (fd[0]
).The closing is not necessary but is usually done. If you need two-way communication you either need a second set of file descriptors plus a second call to
pipe
, or you use a two way channel like Unix domain sockets or a named pipe.pipe 的 Linux 手册页
消除了歧义,如下所示:
也就是说,您从
fd[0]
中读取
并写入
到fd[1]
The Linux man page for
pipe
disambiguates this as follows:That is, you
read
fromfd[0]
andwrite
tofd[1]