简体   繁体   English

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

[英]Read file in non-blocking mode on Linux

When opening the file /dev/urandom in nonblocking mode it is still blocking when reading. 在非阻塞模式下打开文件/ dev / urandom时,它在读取时仍处于阻塞状态。 Why is the read call still blocking. 为什么读取调用仍然阻塞。

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

The output looks like this: 输出看起来像这样:

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

/dev/urandom is non-blocking by design : /dev/urandom 在设计上非阻塞的

When read, the /dev/random device will only return random bytes within the estimated number of bits of noise in the entropy pool. 读取时, /dev/random设备将仅返回熵池中估计的噪声位数内的随机字节。 /dev/random should be suitable for uses that need very high quality randomness such as one-time pad or key generation. /dev/random应该适合需要非常高质量的随机性的应用,例如一次性填充或密钥生成。 When the entropy pool is empty, reads from /dev/random will block until additional environmental noise is gathered. 当熵池为空时,从/dev/random读取将被阻塞,直到收集到其他环境噪声为止。

A read from the /dev/urandom device will not block waiting for more entropy. /dev/urandom设备进行的读取不会阻止等待更多的熵。 As a result, if there is not sufficient entropy in the entropy pool, the returned values are theoretically vulnerable to a cryptographic attack on the algorithms used by the driver. 结果,如果在熵池中没有足够的熵,则返回值在理论上容易受到驱动程序使用的算法的加密攻击。

If you replace it with /dev/random , your program should produce a different result. 如果将其替换为/dev/random ,则程序应产生不同的结果。

Opening any (device) file in nonblocking mode does not mean you never need to wait for it. 以非阻止模式打开任何(设备)文件并不意味着您不需要等待它。

O_NONBLOCK just says return EAGAIN if there is no data available. O_NONBLOCK只是说如果没有可用数据则返回EAGAIN。

Obviously, the urandom driver always considers to have data available, but isn't necessarily fast to deliver it. 显然,urandom驱动程序始终认为有可用数据,但不一定很快就可以提供。

In Linux, it is not possible to open regular files in non blocking mode. 在Linux中,无法以非阻止模式打开常规文件。 You have to use the AIO interface to read from /dev/urandom in non blocking mode. 您必须使用AIO接口以非阻塞模式从/ dev / urandom读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM