如何解决pipe后跟write引发“错误的文件描述符”错误
我不确定这是琐碎的还是对整个pipe()函数的错误理解。这是我问题的最小版本。
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
int main(void) {
int socket[2],r,buff[512];
const char* msg = "what is wrong with pipes";
r = pipe(socket);
if(r < 0) perror("pipe()");
r = write(socket[0],msg,sizeof(*msg));
if(r < 0) perror("write()");
r = read(socket[1],buff,sizeof(*msg));
if(r < 0) perror("read()");
return 0;
}
在Linux上gcc 9.2.1上编译时,该程序始终生成以下输出
write(): Bad file descriptor
read(): Bad file descriptor
这里的代码到底是什么问题?我确实知道应该在具有多个过程的IPC设置中使用它。但是,为什么这段代码不起作用?从我对pipe&pipe2上的人的阅读,书写和阅读中,我看不到任何明显的错误。
解决方法
您必须交换[0]
和[1]
。 [1]
是写端,[0]
是读端。
对于使用的C库函数,请最好阅读/理解MAN页:man for pipe
从pipe(2)手册页:
pipe() creates a pipe,a unidirectional data channel that can be used
for interprocess communication. The array pipefd is used to return two
file descriptors referring to the ends of the pipe. pipefd[0] refers
to the read end of the pipe. pipefd[1] refers to the write end of the
pipe. Data written to the write end of the pipe is buffered by the
kernel until it is read from the read end of the pipe.
For further details,see pipe(7).
注意,尤其是:
pipefd [0]是指管道的读取端。
和
pipefd [1]是指管道的写端。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。