This the continuation of my previous blog http://sivan11in.blogspot.in/2013/10/increasing-file-io-performance-with-mmap.html .
mmap as I said earlier, map the entire file into memory as big long array.
mmap's operation is limited by the following system variables.
Some explanations...
mmap as I said earlier, map the entire file into memory as big long array.
mmap's operation is limited by the following system variables.
- The amount of free memory the system has at that of point of time.
- The amount of fragmentation in the file which you are aiming at.
- The reading mode of the file i.e sequential / random.
There are lot of flags available with mmap which can help you to specify what level of mapping you want mmap to do while mapping you file.
For example, if you mapping a file for a sequential read operation, then you can use MAP_POPULATE as the flag for mmap. This will make the mmap to perform some thing knows as readhead which will read the file for the specified length and populate the pagetable so that your read operations does not have to go through a traditional I/O call . This will improve the performance to a greater extent.
#include "stdio.h"
#include "stdlib.h"
#include "sys types.h"
#include "sys stat.h"
#include "unistd.h"
#include "fcntl.h"
#include "sys/mman.h" // This is the header file for mmap
int main(int argc, char *argv[])
{
char *pMapped;
struct stat fileStat;
if (argc != 3 || (fdin = open (argv[1], O_RDONLY) < 0)
{
printf ("usage: ");
exit(-1);
}
fstat (fdin,&fileStat)
printf("\n Mapping file %s for size %d", argv[1], fileStat.st_size);
/* Now the file is ready to be mmapped.
*/
pMapped = mmap(0, fileStat.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_POPULATE, fdin, 0);
if (pMapped == MAP_FAILED) {
close(fdin);
perror("Error mmapping the file");
exit(EXIT_FAILURE);
}
/* Here afterwards, pMapped can be used as a normal array pointer */
printf("accessing 5 element of the file %c", pMapped[4]);
if (munmap(pMapped, fileStat.st_size) == -1) {
perror("Error un-mmapping the file");
/* Decide here whether to close(fdin) and exit() or not. Depends... */
}
/* Un-mmaping doesn't close the file, so we still need to do that.
*/
close(fdin);
return 0;
}
PROT_READ | PROT_WRITE means mmapped file can be either read / written.
MAP_PRIVATE | MAP_POPULATE means the mapped portion is private only to this process. It is not shared with other processes. If you want to do so, replace MAP_PRIVATE with MAP_SHARED.
MAP_POPULATE as explained earlier performs readahead.
It is always preferable to use stat structure to get the file size rather than lseek from 0 to EOF.
MAP_PRIVATE | MAP_POPULATE means the mapped portion is private only to this process. It is not shared with other processes. If you want to do so, replace MAP_PRIVATE with MAP_SHARED.
MAP_POPULATE as explained earlier performs readahead.
It is always preferable to use stat structure to get the file size rather than lseek from 0 to EOF.
that's the end of tutorial :-)