Search code examples
clinuxposixshared-memory

shm_open() fails while reopening with same name though O_CREAT is used again


According to the http://man7.org/linux/man-pages/man3/shm_open.3.html, it says that

 After a successful shm_unlink(), attempts to shm_open() an object with the same name fail (unless O_CREAT was
 specified, in which case a new, distinct object is created).

S, i tried this one. I am using the below example which creates new shared memory object after doing shm_unlink and as they said i use the O_CREAT.

But when i run this problem, it gives me error related bus error.

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>

int main(void) {
    // Open shared memory
    int fd = shm_open("TEST", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
    ftruncate(fd, sizeof(int));

    // Map shared memory
    int *shm = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd,0);
    close(fd);

    // Access shared memory
    *shm = 0;

    // Unmap shared memory
    munmap(shm, sizeof(int));

    if(shm_unlink("TEST")){
        printf("************success****************");
    }

    fd = shm_open("TEST", O_CREAT |O_RDWR, S_IRUSR | S_IWUSR);
    int *shm2 = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd,0);
    *shm2 = 0;

    return 0;
}

What is the right process of creating the shared memory with the same name again after doing shm_unlink.


Solution

  • You are accessing wrong shared memory in your second attempt (it should be shm2, not shm), and do not forget truncate.

    Also not relevant but shm_unlink returns 0 on success.

    #include <sys/mman.h>
    #include <unistd.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <stdio.h>
    
    int main(void) {
        // Open shared memory
        int fd = shm_open("TEST", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
        ftruncate(fd, sizeof(int));
    
        // Map shared memory
        int *shm = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd,0);
        close(fd);
    
        // Access shared memory
        *shm = 0;
    
        // Unmap shared memory
        munmap(shm, sizeof(int));
    
        if(!shm_unlink("TEST")){
            printf("************success****************");
        }
    
        fd = shm_open("TEST", O_CREAT |O_RDWR, S_IRUSR | S_IWUSR);
        int *shm2 = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd,0);
        ftruncate(fd, sizeof(int));
        *shm2 = 0;
    
        return 0;
    }