问题描述
当前,我想使用shm_open来获取文件描述符,然后在想向共享内存中添加新缓冲区时使用ftruncate和mmap.每个缓冲区都有各自的用途.
Currently I use shm_open to get a file descriptor and then use ftruncate and mmap whenever I want to add a new buffer to the shared memory. Each buffer is used individually for its own purposes.
现在我需要做的是任意调整缓冲区大小.还有munmap缓冲区,以后再重新使用可用空间.
Now what I need to do is arbitrarily resize buffers.And also munmap buffers and reuse the free space again later.
我可以针对第一个问题提出的唯一解决方案是:ftuncate(file_size + old_buffer_size + extra_size),mmap,将整个数据复制到新缓冲区中,然后对原始数据进行映射.这对我来说看起来非常昂贵,并且可能有更好的方法.这也需要每次都删除原始缓冲区.
The only solution I can come up with for the first problem is: ftuncate(file_size + old_buffer_size + extra_size), mmap, copy data accross into the new buffer and then munmap the original data. This looks very expensive to me and there is probably a better way. It also entails removing the original buffer every time.
对于第二个问题,我什至没有不好的解决办法,每次清除缓冲区时,我显然都无法移动内存.而且,如果我跟踪空闲内存并在任何可能的地方使用它,那将会减慢分配过程的速度,并留给我剩余的零碎内存.
For the second problem I don't even have a bad solution, I clearly can't move memory around everytime a buffer is removed. And if I keep track of free memory and use it whenever possible it will slow down allocation process as well as leave me with bits and pieces in between that are unused.
我希望这不要太令人困惑.谢谢
I hope this is not too confusing.Thanks
推荐答案
我为此目的编写了一个开源库: rszshm-可调整大小的指针安全共享内存
I wrote an open source library for just this purpose:rszshm - resizable pointer-safe shared memory
要在描述页面中引用:
我通过在原始地址使用新大小的MAP_FIXED调用mmap来扩展映射.
I extend a mapping by calling mmap with MAP_FIXED at the original address, and with the new size.
这篇关于如何实现动态共享内存大小调整?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!