Benefits of MMAP:
- There will be no unrelated copies compared to read and write system calls;
- Without errors, there will be no overhead such as system calls and operating environment switching;
- Lseek is no longer required.
Disadvantages of MMAP:
- Memory ing is always an integer multiple of pagesize, which wastes a certain amount of memory;
- If the content to be mapped is very large, continuous linear address space may not be found;
- Create and maintain kernel-related data structures. This part may offset the overhead saved by dual copies, especially large files that are frequently accessed.
The following is a comprehensive example of file ing:
Int main (){
// Get the page size
// Int pagesize = sysconf (_ SC _pagesize );
Int pagesize = getpagesize ();
Printf ("system page size: % d \ n", pagesize );
Int I, Len, FD = open ("test", o_rdwr );
Char * P;
// Map the file through MMAP
P = (char *) MMAP (0, 10, prot_read | prot_write, map_shared, FD, 0 );
If (P = map_failed ){
Printf (" ing file failed \ n ");
Return 1;
} Else {
Printf (" ing file successful, file content: % s \ n", P );
Printf (" ing start position: % u \ n", (unsigned INT) P );
Printf ("remainder of the start position on page_size: % d \ n", (INT) P) % pagesize );
Len = strlen (P );
// Convert all characters in test to 'A'
For (I = 0; I <Len; I ++ ){
* (P + I) = 'a ';
}
// Adjust the ing size. mremap_maymove indicates that the ing is movable.
P = (char *) mremap (p, 10, 20, mremap_maymove );
If (P = map_failed ){
Printf ("failed to change the ing size! \ N ");
} Else {
Printf (" ing size changed! \ N ");
}
// Modify the memory access permission
I = mprotect (p, 20, prot_read );
If (P = map_failed ){
Printf ("failed to change access permission! \ N ");
} Else {
Printf ("access permission changed! \ N ");
}
// * P = 'B'; this will cause a segment Error
// Provide kernel suggestions (pre-read)
I = madvise (p, 20, madv_willneed );
If (I =-1 ){
Printf ("Suggestion failed! \ N ");
} Else {
Printf ("Suggestion successful! \ N ");
}
// Unmap
I = munmap (p, 10 );
If (I =-1 ){
Printf ("failed to unmap! \ N ");
} Else {
Printf ("The ing is successfully unbound! \ N ");
}
}
Close (FD );
Return 0;
}