I am using Qt to map a file to a piece of memory pages
QFile::map (qint64 offset, qint64 size, MemoryMapFlags flags = NoOptions)
Essentially, this should be a mmap
system function call. I wonder how I can guarantee that I can access the returned memory, even if the file on disk is truncated. I seem to need this because I read from a disk file and want to gracefully handle errors
if (offset > m_file.size())
// throw an error...
if (m_mappedFile != NULL) return m_mappedFile + offset;
Obviously, this contains a race condition, because the file size may change in between the check and the access to the mapping. How can this be avoided?
A memory-mapped file contains the contents of a file in virtual memory. This mapping between a file and memory space enables an application, including multiple processes, to modify the file by reading and writing directly to the memory.
Step 2 − Map the file contents into memory using mmap() system call. This would return the start address after mapped into the memory. Step 3 − Access the file contents using array notation (can also access with pointer notation) as doesn't read expensive read() system call.
Memory-mapping is a mechanism that maps a portion of a file, or an entire file, on disk to a range of addresses within an application's address space. The application can then access files on disk in the same way it accesses dynamic memory.
Memory-mapped files are casual special files in Java that help to access content directly from memory.
From 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).
So you have to install a signal handler for SIGBUS (default is to crash program)
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