是否可以通过名称打开共享内存段?

发布于 2024-12-18 22:49:54 字数 139 浏览 4 评论 0 原文

char* openSharedMemory(string name);

上面的功能可以实现吗?给定一个名称,打开具有该名称的共享内存段并将句柄返回到共享内存。如果给定名称的共享内存不存在,则创建一个并返回句柄。

char* openSharedMemory(string name);

Is it possible to implement the function above? Given a name, open the shared memory segment with that name and return the handle to the shared memory. If shared memory with the given name does not exist, create one and return the handle.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

孤者何惧 2024-12-25 22:49:54

是的,看看 shm_overview( 7) 如果您使用的是最新的 Unix,shm_open(3)

Yes, take a look at shm_overview(7) if you are on any recent Unix, shm_open(3) in particular.

病女 2024-12-25 22:49:54

可移植的是,您可以使用 Boost.Interprocess

在 Posix 上,您可以这样做:

#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>

const size_t SHARED_MEMORY_SIZE = whatever;

char* openSharedMemory(std::string const &name)
{
    int fd = shm_open(name.c_str(), O_RDWR, 0);
    if (fd < 0) {
        // failed to open existing file, try to create a new one
        fd = shm_open(name.c_str(), O_RDWR | O_CREAT, 0666);
        if (fd < 0 || ftruncate(fd, SHARED_MEMORY_SIZE) != 0) {
            return NULL;
        }
    }
    return static_cast<char*>(
        mmap(NULL, SHARED_MEMORY_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0));
}

尽管您应该将其包装在一个类中,但要保留文件描述符,以便它可以在销毁时取消映射并关闭共享内存对象。

Portably, you can use Boost.Interprocess.

On Posix, you could do something like this:

#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>

const size_t SHARED_MEMORY_SIZE = whatever;

char* openSharedMemory(std::string const &name)
{
    int fd = shm_open(name.c_str(), O_RDWR, 0);
    if (fd < 0) {
        // failed to open existing file, try to create a new one
        fd = shm_open(name.c_str(), O_RDWR | O_CREAT, 0666);
        if (fd < 0 || ftruncate(fd, SHARED_MEMORY_SIZE) != 0) {
            return NULL;
        }
    }
    return static_cast<char*>(
        mmap(NULL, SHARED_MEMORY_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0));
}

Although you should wrap it in a class, to keep hold of the file descriptor so it can unmap and close the shared memory object on destruction.

枕花眠 2024-12-25 22:49:54

如果是 Windows,请考虑使用内存映射文件。

If Windows, look into using a memory-mapped file.

揽清风入怀 2024-12-25 22:49:54

在 Windows 上,查看 MemoryMappedFiles 和 CreateFileMapping 以及名称

On windows look at MemoryMappedFiles and CreateFileMapping with a name

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文