首页 > 解决方案 > 如何在不取消链接的情况下关闭 shm_open 文件描述符?

问题描述

我有一个公共共享内存空间,多个进程可以对其进行读写。我在使用shm_open()访问共享内存和mmap()写入内存映射文件时遇到了这个问题。但是,在对我的包装器方法进行几次调用后,ERRNO 24当我调用shm_open().

我尝试使用shm_unlink(),但这会关闭与共享内存空间关联的名称,并且我无法再次使用关联名称访问该内存。如何关闭文件描述符并将名称与共享内存相关联?

本质上我希望包装函数这样做:

public static void Write(string name, int size, int offset, List<byte> data)
{
    int fd = shm_open(name, O_RDWR, S_IWUSR | S_IWOTH);
    if(fd < 0)  { // throw error }

    IntPtr *ptr = mmap(null, shmSize, PROT_WRITE, MAP_SHARED, fd, 0);
    if(ptr < 0) { // throw error }

    foreach(byte in data) { // write to shared memory }

    munmap(ptr, shmSize);

    shm_close(fd) // <-- I want to do equivalent of this

}

让事情变得更复杂一些。我在 Linux 环境中使用 C# 进行开发,并使用 DLL 导入来调用 Linux 本机函数。

标签: c#cembedded-linuxshared-memorymemory-mapped-files

解决方案


The close function is the mechanism for closing any type of file descriptor, including ones referring to shared memory.


推荐阅读