linux: munmap shared memory in on single call

时间:2016-04-25 09:07:21

标签: linux shared-memory mmap

If a process calls mmap(...,MAP_ANONYMOUS | MAP_SHARED,...) and forks N children, is it possible for any one of these processes (parent or descendants) to munmap() the memory for all processes in one go, thus releasing the physical memory, or does every of these processes have to munmap() individually? (I know the memory will be unmapped on process exit, but the children won't exit yet).

Alternatively, is there a way to munmap memory from another process? I'm thinking of a call something like munmap(pid,...).

Or is there a way to achieve what I am looking for using non-anonymous mappings and performing an operation on the related file descriptor (e.g closing the file)?

My processes are performance sensitive, and I would like to avoid performing lots of IPC when it becomes known that the shared memory will no longer be used by anyone.

1 个答案:

答案 0 :(得分:2)

  1. 不,没有办法一次性取消映射内存。
  2. 如果您根本不需要在子进程中映射内存,则可以在分叉之前使用madvise(MADV_DONTFORK)标记映射。
  3. 在紧急情况下,您可以使用gdb从外部进程内部调用系统调用:

    1. 找出目标流程的PID
    2. 使用cat /proc/<PID>/maps
    3. 列出映射的内存
    4. 使用gdb附加到进程:gdb -p <PID>(它将暂停执行目标进程)
    5. 从gdb:call munmap(0x<address>, 0x<size>)为您需要取消映射的每个区域运行
    6. 退出gdb(恢复进程执行)
    7. 显然,如果您的进程尝试访问未映射的内存,它将接收SIGSEGV。所以,你必须100%确定你在做什么。

相关问题