【发布时间】:2011-10-23 15:20:33
【问题描述】:
最近我开始怀疑我错误地使用了管道的末端:
来自手册页:
pipe() 创建一个管道.. ..pipefd[0] 指的是读端 管道。 pipefd[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;
}
即写入管道的输出(?)并从管道的输入(?)读取?
【问题讨论】:
-
尝试检查读写返回的错误,一切都会变得清晰。
-
读取管道的末端 = 您从中读取的位置 =
pipefd[0](不是您 写入 到的部分,如您的图表中所示)。听起来很简单。 -
@Jon 当我想到物理管道时,我认为它有一个输入角(取水)和一个输出角(放水)。我不认为水会流(写)到管道的输出端。这在我看来是违反直觉的。不,我不是管道工。
-
@Pithikos:在这种情况下,物理管道隐喻确实弊大于利。 :)
-
图表中的箭头与应有的相反。画它们指向相反的方向。
标签: c pipe file-descriptor