File Operations are indispensable.
However, memory ing is often used in mass data storage and limited resource systems. Through file ing, all or part of the disk file is mapped to a region in the virtual address space of the process. You can directly access the mapped file, instead of performing read/write or other file I/O operations, you do not need to buffer the file content. In MongoDB, when the service is started, the data files will be mapped to the memory. For more information, see <MongoDB source code analysis> of Dai, or directly go to MongoDB.
In addition, the memory ing can also be used for data sharing between processes. This is especially true for large data synchronization. The so-called internal implementation of sharedmemory in N multi-library is memorymappedfile.
Below are some code for the memory ing file:
Memorymappedfile:
class MemoryMappedFileImpl : public BedRock::UnCopyable
{
public:
bool attach(const BedRock::WideString& filePath);
void detach();
private:
HANDLE m_fileHandle;
HANDLE m_fileMappedHandle;
BedRock::UInt8* m_fileBuffer;
size_t m_length;
};
Map File to memory:
bool MemoryMappedFileImpl::attach(const BedRock::WideString& filePath)
{
m_fileHandle = CreateFile(filePath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
SMCP_ASSERT(m_fileHandle);
if(m_fileHandle == INVALID_HANDLE_VALUE) return false;
BY_HANDLE_FILE_INFORMATION fileInformation;
BOOL bStatus= GetFileInformationByHandle( m_fileHandle, &fileInformation);
m_length = (size_t) fileInformation.nFileSizeLow; // 32bit only for now.
m_fileMappedHandle = ::CreateFileMapping(m_fileHandle, NULL, PAGE_READONLY, 0, m_length, NULL);
if(m_fileMappedHandle)
{
m_fileBuffer = static_cast<BedRock::UInt8*>(MapViewOfFile( m_fileMappedHandle, FILE_MAP_READ, 0, 0, m_length));
}
return m_fileBuffer != NULL;
}
Unmap:
void MemoryMappedFileImpl::detach()
{
m_filePath.empty();
m_length = INVALID_FILE_SIZE;
if (m_fileBuffer)
{
::UnmapViewOfFile(m_fileBuffer);
m_fileBuffer = NULL;
}
if( m_fileMappedHandle != INVALID_HANDLE_VALUE )
{
::CloseHandle( m_fileMappedHandle );
m_fileMappedHandle = INVALID_HANDLE_VALUE;
}
if( m_fileHandle != INVALID_HANDLE_VALUE )
{
::CloseHandle( m_fileHandle );
m_fileHandle = INVALID_HANDLE_VALUE;
}
}
-
More materials:
Windows core programming
The memory ing of the program design in the Windows System