0

If I use mmap on some file descriptor fd, will regular calls to read() be "aware" that there is a memory mapping of the file and read from memory directly?

What if mlock() is used after mmap(). Is it correct to say that no subsequent read() on the file will ever need to access the disk?

1 Answer 1

2

I guess it depends on what you mean by "aware".

Insofar as the read()s system call is a request to the kernel to copy the contents of a file starting at the present position to the program's designated memory buffer, read() on a regular file will accomplish this task the same way whether or not there is concurrently a memory mapping of the file. There is no "awareness".

Now, it the file is both mmap()ed and read(), there may well be a performance optimization to be achieved. For example, if the file is read() first, then the sections of the file that have been read are probably already in the page cache and subsequently accessing the memory mapping will not have to access them again from disk. Or conversely, if there is a memory mapping that has already been paged in, a subsequent read() will not have to go to disk again. So in that sense you might, in some sense, consider the mmap() and read() "aware" of each other.

3
  • Thanks. What if mlock() is used on top of mmap()? Is it correct to say that after that no read() will ever need to access the disk?
    – ElefEnt
    Feb 18, 2017 at 0:57
  • I think that's probably usually true. There might be some corner cases where it's not guaranteed?
    – Celada
    Feb 18, 2017 at 16:45
  • But using mlock will probably slow the rest of the system, because of lack of memory. This could even cause the rest of the system to get in the way of your process. Jan 27, 2021 at 19:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .