Destroying Memory Mappings

With the exception of the MAP_INHERIT flag for FreeBSD, the memory-mapped regions are unmapped automatically by the kernel when execve(2) is called or when the process terminates. It may occur in an application, however, that the memory-mapped file is needed only temporarily. The munmap(2) system call is used to unmap it:

#include <sys/types.h>
#include <sys/mman.h>

int munmap(void *addr, size_t len);

The memory region to be unmapped is specified as the region starting at addr for a length of len bytes. The function munmap(2) returns 0 when successful. Otherwise, -1 is returned, with an error code left in errno. It should be noted that this system call does not cause pending changes to be written out to the file. If this is important, you must make appropriate use of the msync(2) system call prior to calling on munmap(2).

Referencing memory after it has been unmapped will cause the signal SIGSEGV or SIGBUS to occur. Some UNIX platforms can return either, depending on the nature of the memory access.

Note

Unfortunately, no platform documents that len can be specified as zero. This forces the application programmer to keep track of the memory region size, so that it can be unmapped successfully at a later time.

This restriction is especially painful when MAP_INHERIT is used with execve(2) to execute a new program. Unless the size of the region has been stored in the memory region itself (or communicated some other way), the new program will not know the correct length to use in a munmap(2) call.


To unmap a region of memory in the Listing 26.2 program (messages.c), the following function call could be added prior to the return statement on line 127:

if ( munmap(msgs,msgs_len+1) == -1 )
    perror("munmap(2)");

In this example, recall that one byte was added to the file's size when it was mapped. Consequently, msgs_len+1 is necessary in the munmap(2) call.

Warning

The munmap(2) system call does not cause pending changes to be written out to the file. If this is important, you must make appropriate use of the msync(2) system call prior to calling munmap(2).


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.193.158