C语言 使用 select() 和 O_NONBLOCK 从 FIFO 读取两次连续写入



我正在尝试编写两个连续的字符串。问题是读者在阅读器上使用O_NONBLOCK时不断问候 EAGAIN。

任何想法为什么它在使用O_NONBLOCK时不起作用,select()不应该照顾这个块吗?

读者.c

#include <fcntl.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
int main() {
    int fd;
    char * myfifo = "/tmp/myfifo";
    mkfifo(myfifo, 0666);
    fd = open(myfifo, O_RDWR | O_NONBLOCK);
    write(fd, "12345678", strlen("12345678"));
    write(fd, "HelloWorld", strlen("HelloWorld"));
    close(fd);
    return 0;
}

作家.c

#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>
char buf[BUFSIZ] = { 0 }, buf2[BUFSIZ] = { 0 };
int read1 = 0, read2 = 0;
int main() {
    int fd = 0, a = 0, b = 0 ; 
    char *myfifo= "/tmp/myfifo";
    mkfifo(myfifo, 0666);
    fd_set set;
    if ((fd = open(myfifo, O_RDWR | O_NONBLOCK)) < 0)
        exit(1);
    while (1) {
        FD_ZERO(&set);
        FD_SET(fd, &set);
        if ((select(fd+1, &set, NULL, NULL, NULL)) < 1)
            exit(1);
        if (FD_ISSET(fd, &set)) {
            int total = 0;
            if ((total = read(fd, buf + read1, sizeof(uint32_t) * 2) - read1) <= 0) {
                fprintf(stderr, "%sn", strerror(errno));
                continue;
            }   
            read1 += total;
            if ((total = read(fd, buf2 + read2, BUFSIZ - read2)) <= 0) {
                fprintf(stderr, "%sn", strerror(errno));
                continue;
            }   
            read2 += total;
            fprintf(stderr, "%s %d, %d, %sn", buf, a, b, buf2);
            memset(buf, 0, BUFSIZ);
            memset(buf2, 0, BUFSIZ);
            read1 = read2 = 0;
        }   
    }   
    return 0;
}

您在循环中两次调用 fd 上的 read,第一个read读取可用数据,第二个read可能会因EAGAIN而失败。您应该在执行任何read之前使用 select 测试就绪情况,而不仅仅是第一个。因为FIFO是流,这意味着你必须保持自己不同数据片段的边界。

char buf[BUFSIZ];
if (FD_ISSET(fd, &set)) {
    int total = 0;
    int off = 0;
    total = read(fd, buf, sizeof buf);
    if (total <= 0) {
            fprintf(stderr, "%sn", strerror(errno));
            continue;
    }
    // retrieve the data based on how many bytes you have read
    if (total >= sizeof(uint32_t) * 2) {
        ...
    }
}   

此外,建议在 FIFO 的读取端打开O_RDONLY,在 FIFO 的写入端打开O_WRONLY

最新更新