For my project I have two tasks 1)Writer : Write value into a structure in shared memory 2)Reader: Read value from the structure
Here is the writer code
struct test {
volatile int read;
volatile int write;
};
int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
struct test *t = (struct test *) shmat(shmid,(void*)0,0);
printf("Going to write into test structure");
t->read = 1;
t->write = 2;
//printf("Data written in memory: %s\n",str);
//detach from shared memory
shmdt((void *)t);
return 0;
}
Here is the reader Code
int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
struct test *t = (struct test *) shmat(shmid,(void*)0,0);
printf("Data read from memory: %d:%d\n",t->read,t->write);
//detach from shared memory
shmdt((void *)t);
// destroy the shared memory
shmctl(shmid,IPC_RMID,NULL);
return 0;
}
When I first run the writer and then the reader , things work fine.
But for debugging, I tried to run both at the same time via lldb. I see if writer, writes t->read = 1 , at the same time it would not get updated in the reader process. It would reflect in reader if it calls shmat after changes are done.
Could anyone please tell me , how to make sure changes in shared memory happens synchronously ?