ptg10805159
528 Advanced I/O Chapter 14
kernel daemons decide when dirty pages arewritten back based on (a) system load and
(b) configuration parameters meant to limit data loss in the event of a system failure.
When the changes arewritten back, they arewritten in units of pages. Thus, if we
modify only one byte in a page, when the change is written back to the file, the entire
page will be written.
If the pages in a shared mapping have been modified, we can callmsyncto flush
the changes to the file that backs the mapping. Themsyncfunction is similar tofsync
(Section 3.13), but works on memory-mapped regions.
#include <sys/mman.h>
int msync(void *addr,size_tlen,intflags);
Returns: 0 if OK,−1 on error
If the mapping is private, the file mapped is not modified. As with the other
memory-mapped functions, the address must be aligned on a page boundary.
Theflagsargument allows us some control over how the memory is flushed. We
can specify theMS_ASYNCflag to simply schedule the pages to be written. If we want
to wait for the writes to complete beforereturning, we can use theMS_SYNCflag. Either
MS_ASYNCorMS_SYNCmust be specified.
An optional flag,MS_INVALIDATE,lets us tell the operating system to discardany
pages that areout of sync with the underlying storage. Some implementations will
discardall pages in the specified range when we use this flag, but this behavior is not
required.
Themsyncfunction is included in the XSI option in the Single UNIX Specification. As such,
all UNIX systems must support it.
Amemory-mapped region is automatically unmapped when the process terminates
or we can unmap a region directly by calling themunmapfunction. Closing the file
descriptor used when we mapped the region does not unmap the region.
#include <sys/mman.h>
int munmap(void *addr,size_tlen);
Returns: 0 if OK,−1 on error
Themunmapfunction does not affect the object that was mapped—that is, the call to
munmapdoes not cause the contents of the mapped region to be written to the disk file.
The updating of the disk file for aMAP_SHAREDregion happens automatically by the
kernel’s virtual memory algorithm sometime after we storeinto the memory-mapped
region. Modifications to memory in aMAP_PRIVATEregion arediscarded when the
region is unmapped.
Example
The program in Figure14.27 copies a file (similar to the cp( 1 ) command) using
memory-mapped I/O.