简体   繁体   English

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

[英]Shared memory segment with different variable types C

I'm using Linux. 我正在使用Linux。

Using shared memory to store a static array of structs between two different programs. 使用共享内存在两个不同程序之间存储结构的静态数组。

Here's a code snippet showing how I create the shared memory block. 这是显示如何创建共享内存块的代码段。

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

So far everything is working fine, and the two programs communicate: One modifying data within the structs and the other printing it out. 到目前为止,一切工作正常,并且两个程序可以通信:一个在结构中修改数据,另一个在打印出来。

I would also like to use two integers within the shared memory to act as 'flags' but how would I attach and access them? 我还想在共享内存中使用两个整数来充当“标志”,但是我将如何附加和访问它们呢? Something along the lines of? 有什么类似的?

int *shmnFlagOne, *nPtr;

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

nPtr = shmnFlagOne;

And then set the pointer to go after the array of structs in the shared memory? 然后设置指针去共享内存中的结构数组之后?

You are right on track. 您是正确的。 You can place these items within your memory as you see fit. 您可以根据需要将这些项目放在内存中。 It looks like you have already allocated the storage for your flags with 看来您已经使用以下命令分配了存储空间:

2 * sizeof(int)

You can access them many ways all of which involve pointer casting. 您可以通过多种方式访问​​它们,所有方式都涉及指针转换。

It would look something like: 它看起来像:

void *shared_memory = shmat(nShmid, NULL, 0);
strPrintJob *shmPrintJob = (strPrintJob *) shared_memory;
int *flags = (int *) shared_memory[sizeof(strPrintJob) * lRetMaxJobs / sizeof(int)];

OK, totally gross. 好的,太过分了 But that would be the minimal change. 但这将是最小的变化。 An alternative is to create another struct to wrap your struct: 一种替代方法是创建另一个结构来包装您的结构:

typedef struct {
    strPrintJob[lRetMaxJobs] printJobs;
    int flags[2];
} PrintJobWrapper;

Now use PrintJobWrapper to access your shared memory as you were before: 现在像以前一样使用PrintJobWrapper访问共享内存:

PrintJobWrapper *print_wrapper = (PrintJobWrapper *) shmat(nShmid, NULL, 0);
print_wrapper->flags[0] = xxx;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM