我在一侧打开fifo进行读取,在另一侧打开进行写入,读取侧关闭他打开的fd。有没有办法知道读者是否在作者端关闭了这个文件描述符? 我希望作者能够收到有关读者是否准备好阅读的任何通知,因为如果没有,我的作者将在写入时被阻止。 writer.c:
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd;
char * myfifo = "/tmp/fifo_pipe";
/* create the FIFO (named pipe) */
mkfifo(myfifo, 0666);
/* write "Hi" to the FIFO */
fd = open(myfifo, O_WRONLY);
write(fd, "Hey", sizeof("Hey"));
/*here is there a posibilty of know that the read side hase close hi's side of the pipe before write? */
write(fd, "test\n", strlen("test\n"));
close(fd);
/* remove the FIFO */
unlink(myfifo);
return 0;
}
读者.c:
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_BUF 1024
int main()
{
int fd;
char * myfifo = "/tmp/fifo_pipe";
char buf[MAX_BUF];
/* open, read, and display the message from the FIFO */
fd = open(myfifo, O_RDONLY);
read(fd, buf, MAX_BUF);
printf("Received: %s\n", buf);
close(fd);
return 0;
}
最佳答案
在没有读取器的情况下对 FIFO 进行写入将引发 SIGPIPE 并最终返回 -1 并将 errno 设置为 EPIPE
。
关于c - 有没有办法知道打开用于写入的文件描述符是否有人在读取端监听?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50119061/