c++ - shmdt后共享内存没有被删除

查看:414
本文介绍了c++ - shmdt后共享内存没有被删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

代码如下,我执行了shmdt并且成功了,但是ipcs -m查看了一下,并没有被删除

计数为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   

解决方案

这个函数只是断开共享内存的连接,可以使用shmctl来删除共享内存。

这篇关于c++ - shmdt后共享内存没有被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆