Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 14.8 Memory-Mapped I/O 525


14.8 Memory-Mapped I/O


Memory-mapped I/O lets us map a file on disk into a buffer in memory so that, when
we fetch bytes from the buffer,the corresponding bytes of the file areread. Similarly,
when we storedata in the buffer,the corresponding bytes areautomatically written to
the file. This lets us perform I/O without usingreadorwrite.

Memory-mapped I/O has been in use with virtual memory systems for many years. In 1981,
4.1BSD provided a different form of memory-mapped I/O with itsvreadandvwrite
functions. These two functions werethen removed in 4.2BSD and wereintended to be
replaced with themmapfunction. Themmapfunction, however,was not included with 4.2BSD
(for reasons described in Section 2.5 of McKusick et al.[ 1996 ]). Gingell, Moran, and Shannon
[ 1987 ]describe one implementation ofmmap.Version 4 of the Single UNIX Specification
moved themmapfunction from an option to the base specification. All POSIX-conforming
systems arerequired to support it.

To use this feature, we have to tell the kernel to map a given file to a region in
memory.This task is handled by themmapfunction.
#include <sys/mman.h>
void *mmap(void *addr,size_tlen,int prot,intflag,intfd,off_toff);
Returns: starting address of mapped region if OK,MAP_FAILEDon error
Theaddrargument lets us specify the address where we want the mapped region to
start. Wenormally set this value to 0 to allow the system to choose the starting address.
The return value of this function is the starting address of the mapped area.
Thefdargument is the file descriptor specifying the file that is to be mapped. We
have to open this file before we can map it into the address space. Thelenargument is
the number of bytes to map, andoffis the starting offset in the file of the bytes to map.
(Some restrictions on the value ofoffaredescribed later.)
Theprotargument specifies the protection of the mapped region.

prot Description
PROT_READ Region can be read.
PROT_WRITE Region can be written.
PROT_EXEC Region can be executed.
PROT_NONE Region cannot be accessed.

Figure 14.25Protection of memory-mapped region

We can specify the protection as either PROT_NONE or the bitwise OR of any
combination ofPROT_READ,PROT_WRITE,andPROT_EXEC.The protection specified
for a region can’t allow moreaccess than theopenmode of the file. For example, we
can’t specifyPROT_WRITEif the file was opened read-only.
Beforelooking at theflagargument, let’s see what’s going on here. Figure14.26
shows a memory-mapped file. (Recall the memory layout of a typical process, shown in
Figure7.6.) In this figure, ‘‘start addr’’ isthe return value frommmap.Wehave shown
Free download pdf