Search code examples
c#cembedded-linuxshared-memorymemory-mapped-files

How do I close a shm_open file descriptor without unlinking it?


I have a common shared memory space that multiple processes can read and write to it. I am running into this problem where I am using shm_open() to the access the shared memory and mmap() to write to the memory mapped file. However, after a few calls to my wrapper method I will run into ERRNO 24 (Too many files opened) when I call shm_open().

I tried using shm_unlink(), but that closes the name associated to the shared memory space, and I am unable to access that memory with the associated name again. How do I close the file descriptor and leave the name associated to the shared memory alone?

Essentially I want the wrapper function to do this:

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

}

To make things a little more complicated. I am developing using C# in Linux environment and using DLL imports to call the Linux native functions.


Solution

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