Search code examples
windowsshared-memorymemory-mapped-files

Windows: Resize shared memory


When I create a shared memory segment on Windows (like CreateFileMapping(INVALID_HANDLE_VALUE, ...)), is there any way to resize it, other than creating a bigger segment and copying the data?

I've read in MSDN that file mappings have a fixed size, but is there possibly some way to make a new mapping over the same memory? Like in Linux, where you can use shm_open() and then ftruncate() and mmap() it again.


Solution

  • The short answer is no - you cannot resize a file mapping once it has been created. The create/copy sequence you describe is the only way I'm aware of to accomplish this with file mappings backed by the system paging file.

    That said, you can manage the file backing your mapping yourself and accomplish this. Start with your own zero-initialized data file, and specify valid handles to it to your calls to CreateFileMapping().

    When you need to resize, close your mappings, extend the file, and recreate your mappings. This would require some synchronization between growth/truncating operations - not trivial, but shouldn't be too difficult either.

    In the end, it's the same old story. Added complexity vs performance.