【发布时间】:2018-06-11 14:54:33
【问题描述】:
我正在使用 Linux。
使用共享内存在两个不同的程序之间存储结构的静态数组。
这是一段代码 sn-p,展示了我如何创建共享内存块。
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);
}
到目前为止一切正常,两个程序进行通信:一个修改结构中的数据,另一个将其打印出来。
我还想在共享内存中使用两个整数作为“标志”,但我将如何附加和访问它们? 类似的东西?
int *shmnFlagOne, *nPtr;
if((shmnFlagOne = shmat(nShmid, NULL, 0)) == -1)
{
perror("shmat");
exit(1);
}
nPtr = shmnFlagOne;
然后将指针设置到共享内存中的结构数组之后?
【问题讨论】:
-
考虑使用 POSIX 共享内存,参见 shm_overview(7)
标签: c linux memory struct shared