如何使用 shmget 跨多个进程共享一块内存

How to share a piece of memory across multiple processes using shmget

所以我正在制作一个程序,该程序将具有多个进程,这些进程都需要访问我定义的结构 'node'。所以我初始化内存如下:

    sharedMemory = (node*)malloc(sizeof(node));//sharedMemory is a global node
    sharedMemory->syskey = sys_key;//just a variable from a function
    segment_id = shmget(sharedMemory->syskey, size, S_IRUSR | S_IWUSR | IPC_CREAT);
    sharedMemory = (node*)shmat(segment_id, NULL, 0);

这似乎很顺利。但是我需要稍后访问这段内存。所以我试图做的是:

    segment_id = shmget(sharedMemory->syskey, size, S_IRUSR | S_IWUSR | IPC_CREAT);
    sharedMemory = (node*)shmat(segment_id, NULL, 0);

然后使用sharedMemory。但是,当我这样做时,sharedMemory 中的所有内容似乎都已重置为 'null'(数组等)。我确信我只是在做一些愚蠢的事情,但文档让我有点困惑。任何帮助将不胜感激。

我发现除了 sharedMemory 是一个全局变量之外,我做的是正确的。每当我调用 shmat 并附加它时,我都需要重新声明它。似乎正在工作。