简体   繁体   中英

Access mmap memory from another process

I've started playing with mmap. I'm trying to create an example workspace that will be then extended to the real case.

This is what I want to achieve:

PROCESS 1:

  • mmap a file (actually a device, but it's okay to generate an example with a text file)

PROCESS 2: (not foked from process 1; just an independent process)

  • read the memory mapped by process 1
  • change some bits
  • write it to a new file

I've read several examples and documentations, but I still didn't find how to achieve this. What I'm missing is:

  • how can process 2 access the memory mapped by process 1, without knowing anything about the opened file?
  • how can I put the mmap content in a new file? I suppose I have to ftruncate a new file, mmap this file and memcpy the content of process 1 memory map to process 2 memory map (then msync)

Side info, I have a message queue opened between the two processes, so they can share some messages if needed (ex. the memory address/size, ...).

Any hints?

Thanks in advance!

MIX

This answer considers you are trying to do this stuff on linux/unix.

how can process 2 access the memory mapped by process 1, without knowing anything about the opened file?

Process 1 passes to mmap[1] the flag MAP_SHARED.

You can:

  • A) Share the file descriptor using unix domain sockets[2].
  • B) Send the name of the file using the queues you mentioned at the end of your message.

Process 2 opens mmap with the flag MAP_SHARED. Modifications to the mmaped memory in Process 1 will be visible for Process 2. If you need fine control of when the changes from process 1 are shown to process 2 you should control it with msync[3]

how can I put the mmap content in a new file? I suppose I have to ftruncate a new file, mmap this file and memcpy the content of process 1 memory map to process 2 memory map (then msync)

Why just don't write the mmaped memory as regular memory with write?

[1] http://man7.org/linux/man-pages/man2/mmap.2.html

[2] Portable way to pass file descriptor between different processes

[3] http://man7.org/linux/man-pages/man2/msync.2.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM