search

Home  >  Q&A  >  body text

Shared memory not deleted after shmdt

The code is as follows, I executed shmdt and it was successful, but ipcs -mchecked it and it was not deleted

Won’t it be automatically deleted after the count reaches 0?

#include <sys/types.h>
#include <sys/shm.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
    key_t key = ftok(".", 'T');
    if (key == -1) {
        fprintf(stderr, "get key failed, error: %s\n", strerror(errno));
        exit(1);
    }

    int shmid = shmget(key, sizeof(int) * 10, IPC_CREAT);
    if (shmid == -1) {
        fprintf(stderr, "get shmid failed, error: %s\n", strerror(errno));
        exit(1);
    }

    void* shmaddr = shmat(shmid, NULL, 0);
    if (shmaddr == (void*)-1) {
        fprintf(stderr, "get shmaddr failed, error: %s\n", strerror(errno));
        exit(1);
    }

    if (shmdt(shmaddr) == -1) {
        fprintf(stderr, "detach failed, error: %s\n", strerror(errno));
        exit(1);
    }

    return 0;
}
# ipcs -m

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status      
0x00000000 1179648    root       0          4          0                       
0x00000000 1212417    root       0          4          0                       
0x00000000 1245186    root       0          4          0                       
0x00000000 1277955    root       0          4          0                       
0x00000000 1310724    root       0          4          0                       
0x00000000 1343493    root       0          4          0                       
0x00000000 1376262    root       0          4          0                       
0x00000000 1409031    root       0          4          0                       
0x00000000 1441800    root       0          4          0                       
0x00000000 1474569    root       0          4          0                       
0x54010004 1671178    root       0          40         0                       
0x00000000 1540107    root       0          4          0   
天蓬老师天蓬老师2734 days ago761

reply all(1)I'll reply

  • 天蓬老师

    天蓬老师2017-06-05 11:12:58

    This function just disconnects the shared memory. You can use shmctl to delete the shared memory.

    reply
    0
  • Cancelreply