0

Is there a way to use one shared memory,

shmid = shmget (shmkey, 2*sizeof(int), 0644 | IPC_CREAT);

For two variables with different values?

int *a, *b;
a = (int *) shmat (shmid, NULL, 0);
b = (int *) shmat (shmid, NULL, 0); // use the same block of shared memory ??

Thank you very much!

JiZzuS
  • 3
  • 1
  • 4

2 Answers2

0

Apparently (reading the manual) shmat gets you here a single block of memory, of size 2*sizeof(int).

If so, then you can just adjust the pointer:

int *a, *b;
a = shmat(shmid, NULL, 0);
b = a+1;

Also, casting here is wrong, for reasons listed here (while the question is about malloc, the same arguments apply)

Community
  • 1
  • 1
milleniumbug
  • 15,379
  • 3
  • 47
  • 71
  • Oh.. Someone in school was teaching us to use casting with malloc.. Can't remember why.. :D Thanks :) – JiZzuS Apr 29 '14 at 12:27
0

I'm not familiar with the shmget and similar, but I imagine if the memory is contiguous just increment the pointer.

int *a, *b;
i = (int *) shmat (shmid, NULL, 0);
a = ((int *) shmat (shmid, NULL, 0)) + 1;

Better still, just write:

int *myMemory = shmat (shmid, NULL, 0);

myMemory[0] = 5;
myMemory[1] = 10;
ilent2
  • 5,171
  • 3
  • 21
  • 30