我正在使用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);
}
目前一切运作良好,两个程序能够相互通信:一个程序修改结构体中的数据,另一个程序将其打印出来。
我还想在共享内存中使用两个整数作为“标志”,但如何附加和访问它们呢? 大致需要这样实现:
int *shmnFlagOne, *nPtr;
if((shmnFlagOne = shmat(nShmid, NULL, 0)) == -1)
{
perror("shmat");
exit(1);
}
nPtr = shmnFlagOne;
然后将指针设置为在共享内存中结构体数组之后?