Mmap /dev/random

devicesmmap

Why is it that I cannot mmap /dev/random or /dev/urandom on Linux?

I get errno 19 which is ENODEV.

When I try the same code with /dev/zero it works.

    int fd = open(path, O_RDONLY);
    assert (fd > 0);

    void* random = mmap(NULL, size, PROT_READ, MAP_PRIVATE | MAP_FILE, fd, 0);
    int err = errno;

    assert (random != MAP_FAILED);

Best Answer

You cannot mmap() /dev/random or /dev/urandom. Nor can you seek() them for that matter. And as a general rule, you cannot mmap() unseekable things. Pipes are another example of things you cannot mmap() because they are not seekable.

/dev/random and /dev/urandom are fundamentally stream-based, sequential access, devices. They produce bytes on demand when you read them. Random access to these devices has no meaning. mmap() implies random access.

Related Question