具有不同变量类型C的共享内存段

时间:2018-01-01 17:42:46

标签: c linux memory struct shared

我正在使用Linux。

使用共享内存在两个不同程序之间存储静态结构数组。

这是一段代码片段,展示了如何创建共享内存块。

typedef struct {
 int ID;
 int nData;
 int time;
} strPrintJob;

size = (sizeof(strPrintJob) * lRetMaxJobs) + (sizeof(int) * 2);
strPrintJob *shmPrintJob;

    //Create data segment
    if((nShmid = shmget(nKey, size, IPC_CREAT | 0666)) < 0)
    {
        perror("shmget");
        exit(1);
    }

    shmPrintJob = (strPrintJob *) shmat(nShmid, NULL, 0);
    if (shmPrintJob == (strPrintJob *)(-1))
    {
        perror("shmat");
        exit(1);
    }

到目前为止,一切工作正常,两个程序进行通信:一个修改结构中的数据,另一个将其打印出来。

我还想在共享内存中使用两个整数作为&#39;标记&#39;但我如何附加和访问它们? 有什么东西?

int *shmnFlagOne, *nPtr;

if((shmnFlagOne = shmat(nShmid, NULL, 0)) == -1)
{
   perror("shmat");
   exit(1);
}

nPtr = shmnFlagOne;

然后将指针设置为在共享内存中的结构数组之后?

0 个答案:

没有答案