Search code examples
cstructmmap

c - Struct in mmap


Context

I thought it would be fine to hack a bit with mmap. I used mmap as an integer array but now I wish to understand the underlyings with a struct stored in mmap.

I cannot figure out how memory will be used when this struct :

typedef struct{
   int a[500];
   char b[500];
}myStruct;

is to be saved in a mmaped file using POSIX shared memory (shm_open..) on disk (say /home/me/theMmap) and not /dev/shm or any tmpfs (which would lead to the exact sizeof myStruct at any time, e.g 500*4 + 500 = 2500 bytes anyway).

Say I have :

myStruct Polo;

and wish to use Polo.a[350] after loading the struct from mmap.

Questions

Is it safe to store the struct that way if it remains on the same host ?

Will storing a large structure in a mmap'd file on disk will enable to lazy load it and not taking all the ram while loading ? And retrieving Polo.a[350] without actually loading everything in memory (but in virtual memory of course) ?

I am a bit lost here.

Thanks


Solution

  • Its pretty straight-forward -- you need to open the file, ensure that it is large enough, and then call mmap:

    int fd = open("/home/me/theMmap", O_RDWR|O_CREAT, 0660);
    ftruncate(fd, sizeof(myStruct));
    myStruct *Polo = mmap(0, sizeof(myStruct), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    

    this gives you a pointer to the mmapped space containing the myStruct object, so you access it as
    Polo->a[350] or whatever.

    You don't have to worry about byte ordering or struct packing or whatever, as long as you are accessing it on a single machine, and using the same definition of myStruct. If you change the definition of myStruct and recompile, or you put the file on a thumb drive and move it to a different machine with a different architecture, then you will have problems.