问题描述
有一个发布者通过许多不同的 fifos/pipes 将数据写入我的程序中的其他客户端。
我知道如果我打开一个带有非阻塞标志的 fifo 进行写入,打开将返回一个 No such address or device
错误。
如果我去掉非阻塞标志,open 将被阻塞,所以只能使用一个管道。我该如何解决这个问题?
这是一个相关的网址,When I try to open a fifo O_WRONLY I get a "No such device or address" error。但没有得到答复。
解决方法
我相信解决您的问题的唯一方法是包含一个基于计时器的轮询循环,您可以尝试每秒打开每个 FIFO 一次。将该部分作为选择/轮询/epoll 循环的一部分。一旦所有这些都打开,您就可以停止这样做。
,epoll 仅适用于文件描述符,并且在成功打开之前您不会拥有文件描述符。您可以通过首先打开 fifo 进行阅读来解决该问题。例如,修改相关问题中的示例程序:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
int fdread;
char *fifoname = "my_fifo";
mkfifo(fifoname,0666);
if ((fdread = open(fifoname,O_RDONLY | O_NONBLOCK)) == -1) {
perror("open read only");
exit(EXIT_FAILURE);
}
int fd;
if ((fd = open(fifoname,O_WRONLY | O_NONBLOCK)) == -1) {
perror("open write only");
exit(EXIT_FAILURE);
}
close(fd);
close(fdread);
printf("everything is fine\n");
exit(EXIT_SUCCESS);
}
这解决了眼前的问题,但可能适用于您的其余设计,也可能不起作用。