Brandon
Brandon

Reputation: 23498

Expected behaviour of shm_unlink?

Does shm_unlink store a reference count to determine when to delete the file?

I ask because I have the following:

Writer:

#include <iostream>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstdio>

using namespace std;

void Sleep(int ms)
{
    usleep(ms * 1000);
}

int main()
{
    int fd = shm_open("/Test", O_CREAT | O_TRUNC | O_RDWR, 0600);
    if (fd != -1)
    {
        ftruncate(fd, 512);
        void *ptr = mmap(0, 512, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        if (ptr)
        {
            sprintf((char*)ptr, "hello");
            std::cout<<"Written & Sleeping\n";
            Sleep(10000);
            munmap(ptr, 512);
        }
        close(fd);
        shm_unlink("/Test");
    }
    return 0;
}

Reader:

#include <iostream>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstdio>

using namespace std;

void Sleep(int ms)
{
    usleep(ms * 1000);
}

int main()
{
    int fd = shm_open("/Test", O_RDWR, 0600);
    if (fd != -1)
    {
        ftruncate(fd, 512);
        void *ptr = mmap(0, 512, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        if (ptr)
        {
            printf("Read: %s\n", (char*)ptr);
            munmap(ptr, 512);
        }
        close(fd);
        shm_unlink("/Test");
    }

    Sleep(1000);

    fd = shm_open("/Test", O_RDWR, 0600);
    if (fd != -1)
    {
        ftruncate(fd, 512);
        void *ptr = mmap(0, 512, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        if (ptr)
        {
            printf("Read: %s\n", (char*)ptr);
            munmap(ptr, 512);
        }
        close(fd);
        shm_unlink("/Test");
    }
    return 0;
}

The writer maps the memory just fine. It shows up in /dev/shm as Test which is expected. The reader can also map it successfully.

However, the reader is only able to memory map the file ONCE. After closing it the first time, it is immediately deleted and the second call to shm_open fails.

Is this the expected behaviour? Is shm_unlink supposed to delete the file even if the writer has it open? It deletes it as soon as the reader calls shm_unlink.

Upvotes: 0

Views: 891

Answers (1)

user149341
user149341

Reputation:

Yes, this is expected behavior. From the manual page:

The shm_unlink() function disassociates the shared memory object specified by name from that name.

It's exactly like unlink() on normal files in that regard.

If you don't want to do that, just close() the file descriptor. No other cleanup is necessary.

Upvotes: 1

Related Questions