[LCP] creating a file descriptor entry for a piece of memory

Paul Gearon gearon at ieee.org
Wed Nov 5 14:01:54 EST 2008


On Tue, Nov 4, 2008 at 6:18 PM, Mark Farnell <mark.farnell at gmail.com> wrote:
> mmap maps a file to the memory space and the anoynomous mode of mmap
> allows allocation of a piece of memory to an address space, then share
> this address space to child processes via fork.

Sure.

> That's great.  However are there any ways to allocate a piece of
> memory and assign it to a file ID (no files actually created on HD or
> in /dev), then I can mmap that file ID as many times as I like?

No, that can't be done. Your options are to not use a file descriptor,
and to use one that is already allocated. You can't attach a file
descriptor after a memory allocation with mmap.

Using shared mode for memory mapping allows you to have multiple
processes to access that memory. But then you need some kind of
mechanism for communicating the memory you want to share. If you spawn
a child, then you can bring a file descriptor with you. Otherwise, you
can use an identifier that maps to the filesystem. This is essentially
the mechanism for communicating with other processes. If you don't
have any way of communicating a "name" like this, then there's no way
for another process to know how to find that same memory.

> The trouble of shm_create is that it creates an entry on the file
> system and therefore if I run multiple programs concurrently (which
> calls shm_create with the same hard-coded name) I will be in trouble.

This is the same deal as for mmap. You need some kind of name to
identify the memory to be shared, and the filesystem is used to
communicate this.

> That memory should be freed if the process quits by any means.

Allocated memory is always freed when processes quit. If it's shared,
then it's freed from the address space of any exiting process, and
will be removed completely when the last process exits.

Paul



More information about the linuxCprogramming mailing list