c++ - 调用 shmdt() 后无法删除共享内存段

标签 c++ c linux ipc shared-memory

我成功地调用了 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  

最佳答案

shmdt() detaches the shared memory segment located at the address specified by shmaddr from the address space of the calling process. The to-be-detached segment must be currently attached with shmaddr equal to the value returned by the attaching shmat() call.

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

关于c++ - 调用 shmdt() 后无法删除共享内存段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44283900/

相关文章:

C++ 避免三重指针

c++ - 无法将 std::unorded_set 与自定义 KeyEqual 进行比较

C 参数多于 scanf 所需的参数

linux - nginx/apache重定向vps上docker容器上的输出端口

linux - 如何在 Ubuntu 中启动 Thunderbird 并最小化启动窗口

c++ - 如何使用 C/C++ 创建 linux 用户?

c++ - const char* 与字符串文字的使用

c++ - 如何在netbeans中注释C函数,因此文档提示将被格式化(粗体,段落...)

c - scanf 返回 2,不是真的

CppCheck 警告 : expression depends on order of evaluation in x = x |= (1 << 3)