zoukankan      html  css  js  c++  java
  • linux 进程间共享内存示例

    写入端:

    #include <iostream>
    #include <unistd.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <sys/shm.h>
    using namespace std;
    
    struct MappingDataType {
        int mappingData;
    };
    
    bool SetUsedPID(string mappingName)
    {
        void *shm = NULL;
        MappingDataType *shared;
        int shmid = shmget((key_t)1234, sizeof(MappingDataType), 0666|IPC_CREAT);
        if(shmid == -1)
        {
            fprintf(stderr, "shmget failed
    ");
            return false;
        }
    
        shm = shmat(shmid, 0, 0);
    
        if(shm == (void*)-1)
        {
            fprintf(stderr, "shmat failed
    ");
            return false;
        }
    
        shared = (MappingDataType*)shm;
        shared->mappingData = ::getpid();
    
        /*if(shmdt(shm) == -1)
        {
            fprintf(stderr, "shmdt failed
    ");
            return false;
        }
    
        if(shmctl(shmid, IPC_RMID, 0) == -1)
        {
            fprintf(stderr, "shmctl(IPC_RMID) failed
    ");
            return false;
        }*/
    
        return true;
    }
    
    int main(int argc, char *argv[])
    {
        bool result = SetUsedPID("abc");
        //打断点,运行读取端
        cout << result << endl;
        return 0;
    }

    读取端:

    #include <iostream>
    #include <unistd.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <sys/shm.h>
    using namespace std;
    
    struct MappingDataType {
        int mappingData;
    };
    
    int GetUsedPID(string mappingName)
    {
        void *shm = NULL;
        MappingDataType *shared;
    
        int shmid = shmget((key_t)1234, sizeof(MappingDataType), 0666 | IPC_CREAT);
    
        if (shmid == -1)
        {
            fprintf(stderr, "shmget failed
    ");
            return 0;
        }
    
        shm = shmat(shmid, 0, 0);
    
        if (shm == (void*)-1)
        {
            fprintf(stderr, "shmat failed
    ");
            return 0;
        }
    
        shared = (struct MappingDataType*)shm;
        int pid = shared->mappingData;
        
        if (shmdt(shm) == -1)
        {
            fprintf(stderr, "shmdt failed
    ");
        }
    
        if (shmctl(shmid, IPC_RMID, 0) == -1)
        {
            fprintf(stderr, "shmctl(IPC_RMID) failed
    ");
        }
        
        return pid;
    }
    
    int main(int argc, char *argv[])
    {
        int pid = GetUsedPID("abc");
    
        cout << pid << endl;    //<================= Put a breakpoint here
        return 0;
    }
  • 相关阅读:
    Bit命令
    Leetcode628. 三个数的最大乘积
    MyBatis中一级缓存和二级缓存
    Docker学习-实战MySQL数据同步
    Docker学习-容器数据卷的使用
    我的健康计划【要常看啊】
    ASCII编码对照表
    KMP算法详解
    Docker学习-制作一个自己的镜像
    Docker学习-Docker镜像的分层原理
  • 原文地址:https://www.cnblogs.com/nanfei/p/11797569.html
Copyright © 2011-2022 走看看