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

I have a structure:

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

I create shared memory for the structure as follows:

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

Then I access the shared memory as follows:

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 correct way to access / change shared memory? Is this a better approach?

(I use System V semaphores for synchronization, and I did not include this code. I just wanted to make sure that I am changing the shared memory correctly / correctly.)

+5
source share
2 answers

That's right, the only thing to note is that you are creating a segment of the shared private part of PRIVATE, which means that you have to somehow pass shmid to any other process that you want to use.

+2

, , . , , , Posix . . sem_overview (7) man page.

+4

All Articles