Trevor Trevor - 1 month ago 5
C Question

Why use shm_open?

What's the advantage of doing:

shm_open
followed a
mmap
?

Why not create a regular file, and then pass that
fd
to
mmap
?

I can't see the advantage of
shm_open
- these are just references, are they not?

I've read the man of the whole family. It seems to me, that the "secret" is in the mmaping action - the file "type" seems to be meaningless.

Any pointers will be good, especially with performance account.

My context is a (cyclic over-writable) buffer (say 128MB) that will be constantly written to be one process, and constantly dumped from by another.

As an example: what's wrong with this open/mmap approach.

EDIT

To be precise, is one of the following better than the other:

fd = open("/dev/shm/myshm.file", O_CREAT|O_RDWR, S_IRUSR | S_IWUSR);
mem = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

vs.

fd = shm_open("/myshm.file", O_RDWR|O_CREATE, S_IRUSR | S_IWUSR);
mem = mmap(...same as before...);


When I created a file with regular
open
under the
/dev/shm
fs, and dumped a Gig of garbage to it, my available memory went down by 1G, and my avaiable disk space remained the same.

What's the difference between the two methods?

nos nos
Answer

If you open and mmap() a regular file, data will end up in that file.

If you just need to share a memory region, without the need to persist the data, which incurs extra I/O overhead, use shm_open().

Such a memory region would also allow you to store other kinds of objects such as mutexes or semaphores, which you can't store in a mmap()'ed regular file on most systems.

Comments