Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.)

like image 831
bfresh Avatar asked Apr 01 '12 19:04

bfresh


People also ask

What is Shmget shared memory?

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.

What is Shmget and shmat?

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.

What is shmat in C?

The shmat() function attaches the shared memory segment associated with the shared memory identifier, shmid, to the address space of the calling process.


2 Answers

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.

like image 110
Basile Starynkevitch Avatar answered Sep 27 '22 19:09

Basile Starynkevitch


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.

like image 30
Chris Dodd Avatar answered Sep 27 '22 19:09

Chris Dodd