I need to transfer some data - char buffer[100000];
- to a child process which is started by me.
Right now I'm using an ordinary file to do so, the parent process writes the data to a file on disk, and the child process reads it from disk and deletes the file. However, that causes unnecessary writes to the disk, so I want to use memory-mapped files instead.
How do I create, write to, and then read from a memory-mapped file in such a way that no data is written to disk, except when the pagefile or swap file is used?
Edit: I forgot to specify that I want to use raw WINAPI functions, so the code doesn't have dependencies. I am researching on how to do it and will post an answer myself when ready, but if someone has ready-made code, they're welcome to save me some effort :)
You can use an anonymous file mapping (David Heffernan's answer goes into more detail on this step) with handle inheritance / handle duplication. For example, pass the HANDLE from the parent process on the command-line, then in the child use
DuplicateHandle
to get a valid HANDLE in the child.The CreateFileMapping documentation says that
But it may be easier just to use a ramdisk.
I just found an excellent MSDN article on how to do it, complete with sample code, which I've pasted below.
First process (sends the data):
Second process (receives the data):
Pass
INVALID_HANDLE_VALUE
as the file handle when callingCreateFileMapping
:You can use either an anonymous file mapping object (pass inheritable handle to child process), or use a named file mapping.