I am using a MemoryMappedFile
to exchange data between two processes. So I created/opened the file like this in both processes:
MemoryMappedFile m_MemoryMappedFile = MemoryMappedFile.CreateOrOpen("Demo", 8);
The file access itself is protected with a global mutex in both processes. Now when I write data to the file which is bigger than the defined length of 8 bytes I do NOT get an exception.
var random = new Random();
var testData = new byte[55];
random.NextBytes(testData);
using (var contentAccessor = m_MemoryMappedFile.CreateViewStream())
{
contentAccessor.Write(testData, 0, testData.Length);
}
So perhaps I am getting something wrong here, but I thought if I create a non persistent memory mapped file with a specified capacity (in my case 8 bytes) it is not allowed to write more data than 8 bytes? Or do I corrupt the memory with my call above? Any explanation would be great?
This is specifically mentioned in the documentation for CreateViewStream():
To create a complete view of the memory-mapped file, specify 0 (zero) for the size parameter. If you do this, the size of the view might be larger than the size of the source file on disk. This is because views are provided in units of system pages, and the size of the view is rounded up to the next system page size.
It is indeed rounded up to the page size. Best thing to do is to use the method overload that lets you set the view size:
using (var contentAccessor = m_MemoryMappedFile.CreateViewStream(0, 8))
{
contentAccessor.Write(testData, 0, testData.Length);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With