As an alternative to standard file I/O, the kernel provides an interface that allows an application to map a file into memory, meaning that there is a one-to-one correspondence between a memory address and a word in the file. The programmer can then access the file directly through memory, identically to any other chunk of memory-resident data—it is even possible to allow writes to the memory region to transparently map back to the file on disk. POSIX.1 standardizes—and Linux implements—themmap()system call for mapping objects into memory. This section will discussmmap()as it pertains to mapping files into memory to perform I/O; in Chapter 8, we will visit other applications ofmmap(). mmap( ) A call to mmap() asks the kernel to map lenbytes of the object represented by the file descriptorfd, starting atoffsetbytes into the file, into memory. Ifaddris included, it indicates a preference to use that starting address in memory. The access permissions are dictated byprot, and additional behavior can be given byflags: #include <sys/mman.h> void * mmap (void *addr, The addr parameter offers a suggestion to the kernel of where best to map the file. It is only a hint; most users pass 0. The call returns the actual address in memory where the mapping begins. Theprotparameter describes the desired memory protection of the mapping. It may be eitherPROT_NONE, in which case the pages in this mapping may not be accessed (making little sense!), or a bitwise OR of one or more of the following flags: PROT_READ PROT_WRITE PROT_EXEC The desired memory protection must not conflict with the open mode of the file. For example, if the program opens the file read-only,protmust not specifyPROT_WRITE. Protection Flags, Architectures, and Security
Theflagsargument describes the type of mapping, and some elements of its behavior. It is a bitwise OR of the following values: MAP_FIXED
MAP_PRIVATE
MAP_SHARED
EitherMAP_SHAREDorMAP_PRIVATEmust be specified, but not both. Other, more advanced flags are discussed in Chapter 8. When you map a file descriptor, the file’s reference count is incremented. Therefore, you can close the file descriptor after mapping the file, and your process will still have access to it. The corresponding decrement of the file’s reference count will occur when you unmap the file, or when the process terminates. As an example, the following snippet maps the file backed byfd, beginning with its first byte, and extending forlenbytes, into a read-only mapping: void *p; p = mmap (0, len, PROT_READ, MAP_SHARED, fd, 0); Figure 4-1 shows the effects of paramaters supplied withmmap()on the mapping between a file and a process’ address space.
blog comments powered by Disqus |
|
|
|
|
|
|
|