pipe() 后跟 write() 抛出 "Bad file descriptor" 错误
pipe() followed by write() throws "Bad file descriptor" error
我不确定这是微不足道的还是对整个 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 设置中使用。但是,为什么这段代码不起作用?我在阅读 man on pipe & pipe2, write and read 时没有发现任何明显的错误。
你必须交换 [0]
和 [1]
。 [1]
为写端,[0]
为读端。
建议 reading/understanding 您使用的 C 库函数的手册页: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]指管道的写端
我不确定这是微不足道的还是对整个 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 设置中使用。但是,为什么这段代码不起作用?我在阅读 man on pipe & pipe2, write and read 时没有发现任何明显的错误。
你必须交换 [0]
和 [1]
。 [1]
为写端,[0]
为读端。
建议 reading/understanding 您使用的 C 库函数的手册页: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]指管道的写端