Joh*_*itb 6 c c++ qt mmap memory-mapped-files
我正在使用Qt将文件映射到一块内存页面
QFile::map (qint64 offset, qint64 size, MemoryMapFlags flags = NoOptions)
Run Code Online (Sandbox Code Playgroud)
从本质上讲,这应该是一个mmap系统函数调用.我想知道如何保证我可以访问返回的内存,即使磁盘上的文件被截断也是如此.我似乎需要这个,因为我从磁盘文件中读取并希望优雅地处理错误
if (offset > m_file.size())
// throw an error...
if (m_mappedFile != NULL) return m_mappedFile + offset;
Run Code Online (Sandbox Code Playgroud)
显然,这包含竞争条件,因为文件大小可能在检查和映射访问之间发生变化.如何避免这种情况?
小智 3
从man mmap:
SIGBUS Attempted access to a portion of the buffer that does not correspond to the file
(for example, beyond the end of the file, including the case where another
process has truncated the file).
Run Code Online (Sandbox Code Playgroud)
所以你必须为SIGBUS安装一个信号处理程序(默认是让程序崩溃)