【问题标题】:shared memory segment can't be removed after call shmdt()调用 shmdt() 后无法删除共享内存段
【发布时间】:2017-05-31 11:45:35
【问题描述】:

我成功调用了shmdt(),但是共享内存段无法删除..

这是我的代码:

#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

# 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(shmid, IPC_RMID, NULL);来移除共享内存段。
  • 当shmid_ds::shm_nattch == 0时,共享内存段会被自动移除???@Gaurav Pathak
  • 不,它只是表明您的共享内存是否附加了任何进程。如果 shmid_ds->shm_nattach == 0 则表示它可以附加到另一个进程。

标签: c++ c linux ipc shared-memory


【解决方案1】:

shmdt() 分离位于该地址的共享内存段 由 shmaddr 从调用进程的地址空间中指定。 要分离的段当前必须附加 shmaddr 等于附加的 shmat() 调用返回的值。

shmdt 仅将调用进程从附加的内存中分离。它将 删除进程创建的共享内存。
有关更多信息,请阅读相应系统调用的手册页。

【讨论】:

    猜你喜欢
    • 2013-03-14
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多