Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507433

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?

Upvotes: 6

Views: 1467

Answers (1)

xtof pernod
xtof pernod

Reputation: 883

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)

Upvotes: 3

Related Questions