Rafi Moor
Rafi Moor

Reputation: 76

Why there are no major page fault on a program that maps a file to memory?

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 ();
}

Upvotes: 2

Views: 474

Answers (2)

Rafi Moor
Rafi Moor

Reputation: 76

Thanks, but how do the page get to the page cache? I've tried running the program immediately after reboot. If the open in the program loaded the page to memory, I should see at least 1 major fault before accessing the page.

Upvotes: 0

Alex Hoppus
Alex Hoppus

Reputation: 3935

You are seeing minor pf, because data is already in page cache.

Try the following (console1):

 $ ./main ./myfile 

 ./myfile is maped to virtual memory at 7f23f3cd6000
 Press Enter to continue

Drop caches after that (console 2)

$ echo 3 > /proc/sys/vm/drop_caches

Press enter && see stat (console 1)

 98
 7f23f3cd6000 accessed
 Press any Enter exit

 $ ps -eo min_flt,maj_flt,cmd | grep main
 77      1 ./main ./myfile

Upvotes: 1

Related Questions