Re: mmap MAP_ANONYMOUS

From: Laurent Bercot <ska-skaware_at_skarnet.org>
Date: Tue, 01 Oct 2013 13:20:03 +0100

> I just discovered a specific option in 'mmap' API, which is MAP_ANONYMOUS.
> If I read correctly, this option is useful to share a specific memory region between child and parent processes.
> This without any file descriptor refereneced in proc entries!!
>
> Am I right??
> Is anybody already use this option??
> Is it as useful at as it seems??
> Any advices, restrictions??

  Hi Vincent,

  * Be aware that MAP_ANONYMOUS is not POSIX. The POSIX mmap() is documented here:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html

  * MAP_ANONYMOUS is commonly used for two things on systems that implement it:
    - To share a memory region between a parent and a child, as you said. However,
it requires that the child does not execve(), since it must have the pointer to
the mmap()ed address.
    - To simply get memory pages from the kernel. That's how most malloc()
implementations work nowadays. (The glibc malloc() uses brk() for small
allocations and mmap() with MAP_ANONYMOUS for big ones.)

  All in all, using it directly is generally not a good idea, even if you're
sticking to Linux and don't care about the nonposixness: it's very low-level,
may have quirks you (or I) haven't thought about, and the same functionality
can be achieved via a slightly higher-level interface with very little overhead.

  To share a memory region between the parent and a child, I would open a file
somewhere in a tmpfs and mmap it. Since it's a tmpfs, it doesn't eat at your
disk, and the mmap() is basically free; and since it's in the filesystem, any
authorized process may access it, so your children can execve(). (Better
create a random unique name for the file and open it in a non-readable
directory so only processes that know the file name can access it.)

  The main drawback of this approach is that you have to manually track open
fds on the file in order to remove it when it's not used anymore. Most
of the time, though, you have a parent in control, it opens the file and
deletes it when it dies, and the children are only users, so that's not a
problem.

  I'm a huge advocate of tmpfs, or RAM filesystems in general. It's a very
convenient way to manage shared memory via a simple API and leave the yucky
implementation and optimization details to the kernel.

  * Although very interesting, this isn't related to skaware. You may have
other answers on competent programming forums such as stackoverflow.com.

-- 
  Laurent
Received on Tue Oct 01 2013 - 12:20:03 UTC

This archive was generated by hypermail 2.3.0 : Sun May 09 2021 - 19:38:49 UTC