简体   繁体   中英

How to know the available size of the shared memory that is used by `shm_open` in C++?

I am working on IPC for my C++ program with the boost library and I find that boost::shared_memory_object will not throw any error if I request a memory size that is larger than its capacity. This issue has been asked at least twice on stack overflow:

Why I can create a shared memory bigger than the size mounted on /dev/shm using POSIX?

and

How to get information about free memory from /dev/shm

As the answer to the first question said, there is no direct way to make sure you will not exhaust the shared memory. The only option for me is to check the available memory size before I request the shared memory. However, from the question

how do i change the shm_open path?

one answer said the directory to the shared memory can be either /dev/shm or /var/run/shm (or anything else I guess). By looking at shm_overview we can also confirm that /dev/shm is not the only path, it is just conventional. So my question is: how can we know the available size of the shared memory on Linux given that we are not sure the directory to the shared memory that shm_open is using?

Any suggestions will be appreciated.

If you want a non-portable solution that's limited to glibc, you can cheat and look at the sources of glibc.

shm_open: https://code.woboq.org/userspace/glibc/sysdeps/posix/shm_open.c.html#shm_open

calls this function to get the base path: https://code.woboq.org/userspace/glibc/sysdeps/posix/shm-directory.c.html

It's kind of hardcoded, doesn't seem to be configurable.

But at least you can call it for yourself:

#include <stdio.h>
extern "C" const char *__shm_directory (size_t *len);
int main() {
    size_t idontcare;
    puts(__shm_directory(&idontcare));
}

(compile with -lpthread )

Then you can check the free space there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM