一个共享内存中的两个变量 [英] Two variables in one shared memory

查看:63
本文介绍了一个共享内存中的两个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用一个共享内存,

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 ??

非常感谢!

推荐答案

显然(阅读手册)shmat 为您提供了一块内存,大小为 2*sizeof(int).

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;

此外,这里的转换是错误的,出于此处列出的原因(虽然问题是关于 malloc,同样的参数适用)

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

这篇关于一个共享内存中的两个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆