简体   繁体   English

从用户空间管理虚拟内存

[英]Manage virtual memory from userspace

What I actually want to do is to redirect writes in a certain memory area to a separate memory area which is shared between two processes. 我真正想要做的是将某个内存区域中的写入重定向到两个进程之间共享的单独内存区域。 Can this be done at user level? 这可以在用户级别完成吗? For example, for some page X. What I want to do is to change its (virtual to physical) mapping to some shared mapping when it's written. 例如,对于某些页面X.我想要做的是在写入时将其(虚拟到物理)映射更改为某些共享映射。 Is this achievable? 这可以实现吗? I need to do it transparently too, that is the program still uses the variables in page X by their names or pointers, but behind the scenes, we are using a different page. 我也需要透明地执行它,也就是程序仍然使用其名称或指针在页面X中使用变量,但在幕后,我们使用的是不同的页面。

What you're trying to do isn't entirely possible, because, at least on x86, memory cannot be remapped on that fine-grained of a scale. 你要做的事情并非完全可能,因为,至少在x86上,内存不能在细粒度上重新映射。 The smallest quantum that you can remap memory on is a 4k page, and the page containing any given variable (eg, X) is likely to contain other variables or program data. 您可以重新映射内存的最小量子是一个4k页面,包含任何给定变量(例如,X)的页面可能包含其他变量或程序数据。

That being said, you can share memory between processes using the mmap() system call. 话虽这么说,您可以使用mmap()系统调用在进程之间共享内存。

Yes, it is possible to replace memory mappings in Linux, though it is not advisable to do it since it is highly non-portable. 是的,可以替换Linux中的内存映射,但不建议这样做,因为它非常不便携。

First, you should find out in what page the X variable is located by taking its address and masking out the last several bits - query the system page size with sysconf(_SC_PAGE_SIZE) in order to know how many bits to mask out. 首先,您应该通过获取其地址并屏蔽最后几位来查找X变量所在的页面 - 使用sysconf(_SC_PAGE_SIZE)查询系统页面大小,以便知道要屏蔽多少位。 Then you can create a shared memory mapping that overlaps this page using the MAP_FIXED | MAP_SHARED 然后,您可以使用MAP_FIXED | MAP_SHARED创建与此页面重叠的共享内存映射 MAP_FIXED | MAP_SHARED flag to mmap(2) or mmap2(2) . MAP_FIXED | MAP_SHARED标志为mmap(2)mmap2(2) You should copy the initial content of the page and restore it after the new mapping. 您应该复制页面的初始内容并在新映射后恢复它。 Since other variables may reside in the same page, you should be very careful about memory layout and better use a dedicated shared memory object. 由于其他变量可能位于同一页面中,因此您应该非常小心内存布局并更好地使用专用的共享内存对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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