Two variables in one shared memory

為{幸葍}努か 提交于 2021-01-29 14:40:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!