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\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;
}