简体   繁体   中英

Shared memory segment with different variable types C

I'm using 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 *print_wrapper = (PrintJobWrapper *) shmat(nShmid, NULL, 0);
print_wrapper->flags[0] = xxx;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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