linux 进程间共享内存示例

你离开我真会死。 提交于 2019-12-03 13:40:13

写入端:

#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\n");
        return false;
    }

    shm = shmat(shmid, 0, 0);

    if(shm == (void*)-1)
    {
        fprintf(stderr, "shmat failed\n");
        return false;
    }

    shared = (MappingDataType*)shm;
    shared->mappingData = ::getpid();

    /*if(shmdt(shm) == -1)
    {
        fprintf(stderr, "shmdt failed\n");
        return false;
    }

    if(shmctl(shmid, IPC_RMID, 0) == -1)
    {
        fprintf(stderr, "shmctl(IPC_RMID) failed\n");
        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\n");
        return 0;
    }

    shm = shmat(shmid, 0, 0);

    if (shm == (void*)-1)
    {
        fprintf(stderr, "shmat failed\n");
        return 0;
    }

    shared = (struct MappingDataType*)shm;
    int pid = shared->mappingData;
    
    if (shmdt(shm) == -1)
    {
        fprintf(stderr, "shmdt failed\n");
    }

    if (shmctl(shmid, IPC_RMID, 0) == -1)
    {
        fprintf(stderr, "shmctl(IPC_RMID) failed\n");
    }
    
    return pid;
}

int main(int argc, char *argv[])
{
    int pid = GetUsedPID("abc");

    cout << pid << endl;    //<================= Put a breakpoint here
    return 0;
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!