问题
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!
回答1:
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)
回答2:
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;
来源:https://stackoverflow.com/questions/23364240/two-variables-in-one-shared-memory