title: Page faults on OS X when reading with MMAP
body: <p>I am trying to benchmark file system I/O on Mac OS X using mmap.</p>
  
  <pre><code>#include &lt;unistd.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;dirent.h&gt;
  #include &lt;sys/stat.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/mman.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;math.h&gt;
  
  char c;
  
  int main(int argc, char ** argv)
  {
          if (argc != 2)
          {
                  printf("no files\n");
                  exit(1);
          }
          int fd = open(argv[1], O_RDONLY);
          fcntl(fd, F_NOCACHE, 1);
          int offset=0;
          int size=0x100000;
          int pagesize = getpagesize();
          struct stat stats;
          fstat(fd, &amp;stats);
          int filesize = stats.st_size;
          printf("%d byte pages\n", pagesize);
          printf("file %s @ %d bytes\n", argv[1], filesize);
          while(offset &lt; filesize)
          {
                  if(offset + size &gt; filesize)
                  {
                          int pages = ceil((filesize-offset)/(double)pagesize);
                          size = pages*pagesize;
                  }
                  printf("mapping offset %x with size %x\n", offset, size);
                  void * mem = mmap(0, size, PROT_READ, 0, fd, offset);
                  if(mem == -1)
                          return 0;
                  offset+=size;
                  int i=0;
                  for(; i&lt;size; i+=pagesize)
                  {
                          c = *((char *)mem+i);
                  }
  
                  munmap(mem, size);
          }
          return 0;
  }
  </code></pre>
  
  <p>The idea is that I'll map a file or portion of it and then cause a page fault by dereferencing it. I am slowly losing my sanity since this doesn't at all work and I've done similar things on Linux before.</p>