c - 有没有办法知道打开用于写入的文件描述符是否有人在读取端监听?

标签 c linux fifo

我在一侧打开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/

相关文章:

linux - 在构建面向性能的 linux 服务器以运行不同的应用程序时如何选择硬件?

python - 在文件中查找字符串并替换整行

linux - bash Linux : start multiple program in parallel and stop all when one has finished

c - 如何让 C 程序阻塞直到 FIFO 管道为空?

c - 如果我取消链接打开的 fifo 管道会怎样?

c - 检测何时从程序打开 fifo

c - Linux 如何为其物理分配器分配内存?

c - lint 错误 18 "Symbol ' CsiNetInit(void)' 重新声明(精度)与第 21 行冲突

混淆 C 指针行为

c - 数组和指针的关系,为什么这段代码不打印 a[i]