记一次Linux共享内存段排除Bug:key值为0x0000000的共享内存段删除不了

本文目录

一、问题情况

今天查看共享内存段发现好多共享内存段,而且命令ipcrm -m <shmid>删除不了。

回想了一下,应该是有一些程序跑while循环,或者死循环,不让进程结束,只要挂接数(nattch)还不为0,说明共享内存还被占用,所以无法删除,但是以dest作为标记,表明只要进程结束,就会自动删除共享内存。

二、解决方法

2.1 通过kill命令删除

通过ipcs -mp查看一些对应的创建者PID。然后Kill -9即可。

来看看kill之后的结果,确实可以删掉。

除了直接查看pid命令,我们也可以通过代码进行获取:

struct shmid_ds结构体原型,shm_cpid是创建共享内存时的pid,shm_lpid是最后一次使用这个共享内存进程的id。所以可以通过构建声明一个结构体类型的shmid_ds保存共享内存的信息。

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main()
{
    int res;
    int id[7] = {1664,1662};   //shmid
    struct shmid_ds ds; //声明一个结构体类型的shmid_ds保存共享内存的信息
    for(int i = 0; i < 2; i++){
        res = shmctl(id[i], IPC_STAT, &ds);  //查询共享内存
        if (res == -1)
        {
            perror("shmctl error!");
            exit(-1);
        }
        printf("cpid = %d, lpid = %d\n", ds.shm_cpid, ds.shm_lpid); //获取创建PID和最后使用的PID
    }
    return 0;
}

2.2 通过程序删除

以使用 shmat 函数将其附加到进程的地址空间,然后使用 shmdt 函数将其分离。这将释放该共享内存段,使其成为不可用状态,最后再删除该共享内存。

cpp 复制代码
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
 
int main() 
{
    int shmid;
    void *shmaddr;
 
    // 获取共享内存标识符
    shmid = shmget(0x00000000, 1, 0);
    if (shmid == -1) {
        perror("shmget");
        return 1;
    }
 
    // 连接共享内存到进程地址空间
    shmaddr = shmat(shmid, NULL, 0);
    if (shmaddr == (void *)-1) {
        perror("shmat");
        return 1;
    }
 
    // 脱离共享内存
    if (shmdt(shmaddr) == -1) {
        perror("shmdt");
        return 1;
    }
 
    // 删除共享内存段
    if (shmctl(shmid, IPC_RMID, NULL) == -1) {
        perror("shmctl");
        return 1;
    }
 
    printf("Shared memory segment detached and deleted successfully.\n");
 
    return 0;
}
相关推荐
碎梦归途3 小时前
思科网络设备配置命令大全,涵盖从交换机到路由器的核心配置命令
linux·运维·服务器·网络·网络协议·路由器·交换机
小天源3 小时前
nginx在centos7上热升级步骤
linux·服务器·nginx
AZ996ZA4 小时前
自学linux第十八天:【Linux运维实战】系统性能优化与安全加固精要
linux·运维·安全·性能优化
大虾别跑4 小时前
OpenClaw已上线:我的电脑开始自己打工了
linux·ai·openclaw
weixin_437044645 小时前
Netbox批量添加设备——堆叠设备
linux·网络·python
hhy_smile5 小时前
Ubuntu24.04 环境配置自动脚本
linux·ubuntu·自动化·bash
宴之敖者、5 小时前
Linux——\r,\n和缓冲区
linux·运维·服务器
LuDvei5 小时前
LINUX错误提示函数
linux·运维·服务器
未来可期LJ6 小时前
【Linux 系统】进程间的通信方式
linux·服务器
Abona6 小时前
C语言嵌入式全栈Demo
linux·c语言·面试