cli2
cli2

Reputation: 249

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.

Upvotes: 1

Views: 5411

Answers (2)

merano
merano

Reputation: 1

See shm_open(3) — Linux manual page

  1. After a call to mmap(2) the file descriptor may be closed without affecting the memory mapping.

  2. The operation of shm_unlink() removes a shared memory object name, and .. deallocates and destroys ...

Upvotes: 0

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215287

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

Upvotes: 4

Related Questions