当我尝试打开一个FIFO O_WRONLY时,我收到“没有这样的设备或地址”错误

在我的代码中,如果我在O_WRONLY中打开它,我会创建一个名为“my_fifo”的fifo O_NONBLOCK模式,open()返回-1,错误号为“No such device or address”,另一方面,如果我在O_RDONLY中打开fifo | O_NONBLOCK模式,它完美地运作.为什么会这样?有什么我做错了吗?

#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[])
{

    char *fifoname = "my_fifo";
    mkfifo(fifoname, 0666);

    int fd;
    if ((fd = open(fifoname, O_WRONLY | O_NONBLOCK)) == -1)
    {
        perror("open pipe");
        exit(EXIT_FAILURE);
    }

    close(fd);

    exit(EXIT_SUCCESS);
}

解决方法:

查看Linux fifo手册页:

A process can open a FIFO in nonblocking mode. In this case, opening
for read-only will succeed even if no-one has opened on the write
side yet, opening for write-only will fail with ENXIO (no such device
or address) unless the other end has already been opened.

如果您想要非阻塞模式,则需要确保阅读器在编写器之前打开fifo.

上一篇:从Python程序写入FIFO


下一篇:无法理解select()系统调用