<p>You can try using <a href="http://man7.org/linux/man-pages/man2/mincore.2.html" rel="nofollow noreferrer"><code>mincore(2)</code></a></p>

<p>This will be non-thread safe, unfortunately. Another thread might allocate that region after you check region status, but before you execute <code>mmap</code>.</p>

<p>If you need to reserve a memory area, just create anonymous private mapping with <code>PROT_NONE</code>. Later you can put different mappings on top of it using <code>MAP_FIXED</code>.</p>

<p>EDIT: Looks like <code>mincore</code> behavior is going to <a href="https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=574823bfab82d9d8fa47f422778043fbb4b4f50e" rel="nofollow noreferrer">change</a> in Linux 5.0 due to the fact that it can cause information leak (<a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-5489" rel="nofollow noreferrer">CVE-2019-5489</a>):</p>

<blockquote>
  <p>So let's try to avoid that information leak by simply changing the
  semantics to be that mincore() counts actual mapped pages, not pages
  that might be cheaply mapped if they were faulted (note the "might be"
  part of the old semantics: being in the cache doesn't actually
  guarantee that you can access them without IO anyway, since things
  like network filesystems may have to revalidate the cache before use).</p>
</blockquote>

<p>Vulnerability description can be found <a href="https://arxiv.org/pdf/1901.01161.pdf" rel="nofollow noreferrer">here</a>.</p>
How can I find if a memory location is free for mmaping?
<p>I really want to reserve a specific set of memory locations with the <code>MAP_FIXED</code> option to <code>mmap</code>. However, by default <code>mmap</code> will <code>munmap</code> anything already at those addresses, which would be disastrous.</p>

<p>How can I tell <code>mmap</code> to "reserve the memory at this address, but fail if it is already in use"?</p>