tags:

views:

25

answers:

1

I am trying to benchmark file system I/O on Mac OS X using mmap.

#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <stdio.h>
#include <math.h>

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, &stats);
        int filesize = stats.st_size;
        printf("%d byte pages\n", pagesize);
        printf("file %s @ %d bytes\n", argv[1], filesize);
        while(offset < filesize)
        {
                if(offset + size > 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<size; i+=pagesize)
                {
                        c = *((char *)mem+i);
                }

                munmap(mem, size);
        }
        return 0;
}

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.

+1  A: 

Change this line

void * mem = mmap(0, size, PROT_READ, 0, fd, offset);

to

void * mem = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, offset);

And, don't compare mem with -1. Use

if(mem == MAP_FAILIED) { ... }

instead.

General advice: if you're on a different UNIX platform from what you're used to, it's a good idea to open the man page. For mmap on OS X, it can be found here. It says

Conforming applications must specify either MAP_PRIVATE or MAP_SHARED.

So, specifying 0 on the fourth argument is not OK in OS X. I believe this is true for BSD in general.

Yuji
+1 indeed this solved my issue.
Novikov