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

时间:2014-03-16 15:27:11

标签: c linux random file-io posix

在非阻塞模式下打开文件/ dev / urandom时,它在读取时仍然阻塞。为什么读取呼叫仍然阻塞。

#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;
}

输出如下:

gcc nonblock.c -o nonblock
./nonblock 
non block is set
bytes read: 10000000

3 个答案:

答案 0 :(得分:4)

/dev/urandomnon-blocking by design

  

读取时,/dev/random设备只返回随机字节          在熵池中估计的噪声比特数内。          /dev/random应该适合需要高质量的用途          随机性如一次性垫或密钥生成。当熵          池是空的,从/dev/random读取将阻止直到另外          收集环境噪音。

     

来自/dev/urandom设备的读取不会阻止等待更多          熵。结果,如果没有足够的熵          熵池,返回值理论上容易受到影响          对驱动程序使用的算法进行加密攻击。

如果将其替换为/dev/random,您的程序应该产生不同的结果。

答案 1 :(得分:3)

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

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

显然,urandom驱动程序总是认为有数据可用,但不一定快速提供它。

答案 2 :(得分:-1)

在Linux中,无法以非阻塞模式打开常规文件。您必须使用AIO接口以非阻塞模式从/ dev / urandom读取。

相关问题