使用 select() 连续读取 FIFO

标签 c linux select named-pipes fifo

当我的主程序在无限循环中运行时,我试图在后台读取 FIFO(使用线程)。我想使用 select(),否则处理器会以 100% 的速度运行,但是适当的 example我发现不起作用。这是示例代码:

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <unistd.h>

int main()
{
    mkfifo("FIFO", 0666);

    fd_set readCheck;
    fd_set errCheck;
    char buffer[64];
    struct timeval timeout;
    int rv;

    int fd = open("FIFO", O_RDONLY | O_RSYNC);

    FD_ZERO(&readCheck);
    FD_ZERO(&errCheck);

    while (1) {
        FD_SET(fd, &readCheck);
        FD_SET(fd, &errCheck);

        timeout.tv_sec = 1;
        timeout.tv_usec = 0;

        rv = select(fd, &readCheck, NULL, &errCheck, &timeout);
        if (rv < 0) {
            printf("Select failed\r\n");
            break;
        }

        if (FD_ISSET(fd, &errCheck)) {
            printf("FD error\r\n");
            continue;
        }

        if (FD_ISSET(fd, &readCheck)) {
            memset(buffer, 0, sizeof(buffer));
            rv = read(fd, buffer, sizeof(buffer));
            if (rv < 0) {
                printf("Read failed\r\n");
                break;
            }
            printf(buffer);
            buffer[64] = '\0';
        }
    }
    close(fd);

    return 0;
}

当我写入 FIFO 文件时没有任何反应,但使用 cat FIFO 打印内容。可能是什么问题?

最佳答案

您必须将第一个参数设置为比上次打开的文件描述符更高的参数。从 select 的手册页中,

nfds is the highest-numbered file descriptor in any of the three sets, plus 1

改变这一行,

rv = select(fd, &readCheck, NULL, &errCheck, &timeout);

rv = select(fd+1, &readCheck, NULL, &errCheck, &timeout);

如果您没有提及这一点,那么 select 将不会检查您的描述符,因此您不会准备好读取文件描述符。

关于使用 select() 连续读取 FIFO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36060067/

相关文章:

php - 从 PHP 运行脚本

MySQL查询关系表

php - MySQL 查询上的正则表达式进行左连接

linux - 在linux中合​​并两个csv文件

ec2 尝试使用 systemd 启动守护进程时出现 Django celery Worker 错误

从mathematica表中选择数据

c - 在已编译 C 代码的汇编 if 语句中使用 "or"助记符

C程序从数组中打印出LCD数字

C 程序 sqrt 不工作

c - 如何定位特定的 Mac OS X 版本?