简体   繁体   English

如何知道 C++ 中`shm_open` 使用的共享内存的可用大小?

[英]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.我正在使用 boost 库为我的 C++ 程序处理 IPC,我发现如果我请求的内存大小大于其容量, boost::shared_memory_object不会抛出任何错误。 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? 为什么我可以使用 POSIX 创建比 /dev/shm 上安装的大小更大的共享内存?

and

How to get information about free memory from /dev/shm 如何从 /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? 我如何更改 shm_open 路径?

one answer said the directory to the shared memory can be either /dev/shm or /var/run/shm (or anything else I guess).一个答案说共享内存的目录可以是/dev/shm/var/run/shm (或我猜的其他任何东西)。 By looking at shm_overview we can also confirm that /dev/shm is not the only path, it is just conventional.通过查看shm_overview我们还可以确认/dev/shm不是唯一的路径,它只是常规路径。 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?所以我的问题是:鉴于我们不确定shm_open正在使用的共享内存的目录,我们如何知道 Linux 上共享内存的可用大小?

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.如果你想要一个仅限于 glibc 的非便携式解决方案,你可以作弊并查看 glibc 的来源。

shm_open: https://code.woboq.org/userspace/glibc/sysdeps/posix/shm_open.c.html#shm_open 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调用此函数以获取基本路径: 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 ) (用-lpthread编译)

Then you can check the free space there.然后你可以检查那里的可用空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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