简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM