Linux上以非阻塞模式读取文件

use*_*328 2 c linux random file-io posix

当以非阻塞模式打开文件 /dev/urandom 时,读取时它仍然是阻塞的。为什么 read 调用仍然阻塞。

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

int main(int argc, char *argv[])
{
    int fd = open("/dev/urandom", O_NONBLOCK);
    if (fd == -1) {
        printf("Unable to open file\n");
        return 1;
    }

    int flags = fcntl(fd, F_GETFL);
    if (flags & O_NONBLOCK) {
        printf("non block is set\n");
    }

    int ret;
    char* buf = (char*)malloc(10000000);

    ret = read(fd, buf, 10000000);
    if (ret == -1) {
        printf("Error reading: %s\n", strerror(errno));
    } else {
        printf("bytes read: %d\n", ret);
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出如下所示:

gcc nonblock.c -o nonblock
./nonblock 
non block is set
bytes read: 10000000
Run Code Online (Sandbox Code Playgroud)

mfr*_*fro 5

以非阻塞模式打开任何(设备)文件并不意味着您永远不需要等待它。

O_NONBLOCK 只是表示如果没有可用数据则返回 EAGAIN。

显然,urandom 驱动程序始终考虑有可用数据,但不一定能快速交付数据。