I am trying to demonstrate paging in Linux. I wrote a small program that maps a file to virtual memory with mmap(), waits for input, access the allocated memory, and waits for input again.
I check the process minor and major faults after mapping the file to memory and after accessing this memory.
I’ve expected to see a major fault, but I only see a minor fault. The number of major faults remains 0 until the program ends. This is very strange, because the kernel must perform an I/O in order to bring the content of the file to memory.
Can anyone explain this?
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/mman.h>
#include <stdio.h>
int main (int argc, char *argv[]) {
char *mblk;
int fd, fsize, n;
struct stat fs;
fd = open ( argv[1], O_RDONLY );
if ( fd == -1 ) {
printf ( "Failed to open %s\n", argv[1] );
return (-1);
}
fstat ( fd, &fs );
fsize = fs.st_size;
mblk = mmap ( NULL, fsize, PROT_READ, MAP_PRIVATE, fd, 0 );
close ( fd );
printf ( "\n %s is maped to virtual memory at %llx\n", argv[1], (unsigned long long) mblk );
printf ( " Press Enter to continue\n");
getchar ();
n = (unsigned) *mblk;
printf ( "%d\n", n);
printf ( " %llx accessed\n", (unsigned long long) mblk );
printf ( " Press any Enter exit\n");
getchar ();
}