How to modify shared memory (shmget/shmat) in C?

2019-04-30 17:34发布

问题:

I have a struct:

struct sdata {
    int x;
    int y;
    time_t time;
};

I create shared memory for the struct as follows:

size_t shmsize = sizeof(struct sdata);
shmid = shmget(IPC_PRIVATE, shmsize, IPC_CREAT | 0666);

Then I access the shared memory like this:

struct sdata *data = shmat(shared.shmid, (void *) 0, 0);
data->time = time(NULL); // function returns the current time

My question is pretty simple. Is this the right way to access/modify shared memory? Is this the best approach?

(I am using System V semaphores for synchronization and I haven't included that code. I just wanted to make sure I am accessing/modifying the shared memory correctly.)

回答1:

This is correct, the only thing of note is that you are creating a PRIVATE shared memory segment, which means you'll have to transmit the shmid somehow to any other process that you want to have use it.



回答2:

Yes, it is a way to create, then access or modify that shared memory. However, you may have sychronizaton issues, and you could use e.g. Posix semaphores for that. See first sem_overview(7) man page.