C - Structure in mmap

Context

I thought it would be nice to hack mmap. I used mmap as an integer array, but now I want to understand the basics with the structure stored in mmap.

I can't figure out how the memory would be used with this structure:

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

      

should be stored in a mmaped file using POSIX shared memory (shm_open ..) on disk (say / home / me / theMmap) and not / dev / shm or any tmpfs (which will result in the exact size of myStruct at anyway, like , 500 * 4 + 500 = 2500 bytes).

Let's say I have:

myStruct Polo;

      

and want to use Polo.a [350] after loading the structure from mmap.

Questions

Is it possible to store a structure this way if it stays on the same host?

Will it store a large structure in a mmap'd file on disk, allow lazy loading, and not accept all data at boot time? And retrieving Polo.a [350] without actually loading everything in memory (but in virtual memory, of course)?

I'm a little lost here.

thank

+3


source to share


2 answers


It's pretty straight forward - you need to open the file, make sure it's big enough, 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 can access it like
Polo->a[350]

or whatever.

You don't have to worry about ordering bytes or packing a struct or whatever as long as you access it from the same machine and use the same definition myStruct

. If you change the definition myStruct

and recompile, or you put the file on a flash drive and move it to another machine with a different architecture, then problems will arise.

+3


source


You are a little embarrassed. shm_open

mainly for sharing memory between processes. If you just want to deal with "persistent" memory, open

+ mmap

is what you want.



+2


source







All Articles