Daniel Kats
Daniel Kats

Reputation: 5554

Map already allocated memory into shared memory

If some memory is already allocated (for example using malloc), is it possible to then share that memory with another process, for example by marking the page as shared?

To be clear, this is distinct from initially allocating the memory as shared memory, for example using shmget and similar. Obviously it is possible to do this with memcpy, but is there a way to do it directly?

Upvotes: 4

Views: 1101

Answers (1)

alamar
alamar

Reputation: 19313

mmap() creates a new mapping in the virtual address space of the calling process.
The starting address for the new mapping is specified in addr.
The length argument specifies the length of the mapping.

So I imagine:

  • Open a file in donor process for writing.
  • mmap() your existing malloc'd memory.
  • Open same file in another process.
  • Enjoy shared memory.

Upvotes: 1

Related Questions