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.)
The shmget function is used to create a new shared memory segment or to locate an existing one based on a key. Shared memory segments are memory areas which can be shared by several processes and which, once created, continue to exist until explicitly deleted using the shmctl function.
shmget() returns the identifier of the System V shared memory segment associated with the value of the argument key. shmat() shmat() attaches the shared memory segment identified by shmid to the address space of the calling process. basically shmget creates a shared memory buffer IPC_CREAT and returns it's ID.
The shmat() function attaches the shared memory segment associated with the shared memory identifier, shmid, to the address space of the calling process.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With