3
votes

Is it possible to create a memory pool shared between processes (for example from CreateFileMapping with INVALID_HANDLE_VALUE in Win32) and then use that chunk of memory as a heap ?

I would like the new/delete operators (or malloc/free) to allocate/free memory from that chunk (and do their usual heap management on it).

Thanks.

EDIT: My real problem is simple: for now I use the new operator to allocate various large series of structures normally, but I want these structures to persist after the process closes. So I would like to create another process whose almost only function is to hold the memory when the main process closes.

For that, I would create a chunk of shared memory with CreateFileMapping in the auxiliary process, and, in the main process, tell those new/delete used to allocate the structures to use that chunk instead of the process's heap.

To recover the structures after the main processes is relaunched, I would add a fixed amount to all the pointers, reflecting the different origins of the mapped view returned by MapViewOfFile.

1
Yes if you implement your own heap manager on top of the file mapping. - Roman R.
Don't forget the synchronization. - Raymond Chen
@Roman my question was precisely how to use the existing heap management logic in malloc/new and not implement it from scratch :) - SemMike
@Raymond if you mean using a simple semaphore bool variable shared between the processes, then I won't forget! - SemMike
Concurrent access, mapping to different addresses in different processes, fixed size of underlying mapping - these are things I immediately thought of that you will need to deal with. It is surely possible to implement all this, I just doubt that you can apply any standard heap management onto it. - Roman R.

1 Answers

1
votes

Thanks to the people who commented.

Answering my own question:

I gave up on making the shared memory a heap, I simply save a fixed snapshot of the structures to the shared memory allocated by the other process with CreateFileMapping. I just do the opposite when the process is relaunched, using OpenFileMapping and MapViewOfFile.