Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ensure that a memory-mapped file keeps the memory pages accessible?

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?

like image 806
Johannes Schaub - litb Avatar asked Mar 28 '13 10:03

Johannes Schaub - litb


People also ask

How the files are mapped into memory explain the file system?

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.

How do you do memory mapping?

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.

What is memory mapping and why it is used?

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.

What is the class that allows access to a region of a file directly from memory?

Memory-mapped files are casual special files in Java that help to access content directly from memory.


1 Answers

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)

like image 171
xtof pernod Avatar answered Oct 12 '22 06:10

xtof pernod