简体   繁体   中英

Read file in non-blocking mode on Linux

When opening the file /dev/urandom in nonblocking mode it is still blocking when reading. 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 :

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 should be suitable for uses that need very high quality randomness such as one-time pad or key generation. When the entropy pool is empty, reads from /dev/random will block until additional environmental noise is gathered.

A read from the /dev/urandom device will not block waiting for more entropy. 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.

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.

Obviously, the urandom driver always considers to have data available, but isn't necessarily fast to deliver it.

In Linux, it is not possible to open regular files in non blocking mode. You have to use the AIO interface to read from /dev/urandom in non blocking mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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