zoukankan      html  css  js  c++  java
  • Linux下C++共享内存

    记录一下。

    send.cpp:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/shm.h>
     
    #define BUFSZ 1024*1024
     
    int main(int argc, char *argv[])
    {
        int shmid;
        int ret;
        key_t key;
        char *shmadd;
        
        //创建key值
        key = ftok(".", 2016);
        
        //创建共享内存
        shmid = shmget(key, BUFSZ, IPC_CREAT|0666);    
        
        //映射
        shmadd = (char*)shmat(shmid, NULL, 0);
    
        //拷贝数据至共享内存区
        printf("copy data to shared-memory\n");
        bzero(shmadd, BUFSZ); // 共享内存清空
        strcpy(shmadd, "how are you, lh");
        
        return 0;
    }

    rev.cpp:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/shm.h>
     
    #define BUFSZ 1024*1024
     
    int main(int argc, char *argv[])
    {
        int shmid;
        int ret;
        key_t key;
        char *shmadd;
        
        //创建key值
        key = ftok(".", 2016);
        
        //打开共享内存
        shmid = shmget(key, BUFSZ, IPC_CREAT|0666);
    
        //映射
        shmadd = (char*)shmat(shmid, NULL, 0);
    
        //读共享内存区数据
        printf("data = [%s]\n", shmadd);
        
        //分离共享内存和当前进程
        ret = shmdt(shmadd);
    
        //删除共享内存
      //  shmctl(shmid, IPC_RMID, NULL);
            
        return 0;
    }

    如果共享内存shmid已存在,可以用ipcs查看,然后ipcrm -m shmid删除即可。

  • 相关阅读:
    adb shell top
    数据清洗的方法
    Devices Tree加载流程
    Android驱动之设备树简介
    序列模式挖掘综述
    python 实现kmeans聚类
    numpy中sum(axis=0)和axis=1的计算原理
    win7 VMware下安装centos和Ubuntu共存
    python数据标准化
    python 用PIL Matplotlib处理图像的基本操作
  • 原文地址:https://www.cnblogs.com/tiandsp/p/15552737.html
Copyright © 2011-2022 走看看