【发布时间】:2014-05-07 18:54:41
【问题描述】:
我在共享内存中遇到了一个问题: 该项目是定义端口数量并让这些端口相互互连, 我必须通过 ubuntu 中的一种相互通信方法(管道、共享内存、消息队列等)来实现这些端口,所以我决定将它们实现为共享内存,段数等于端口数。
我的问题是,当我将具有相同密钥和相同 ID 的共享内存附加到不同的进程时,shmat() 函数返回指向同一共享内存的不同指针! 所以每个进程都有自己的共享内存! ...为什么会这样?谢谢
int ringget(key_t key, int size, ring_t* info)
{
int shm_ID = shmget(key, sizeof(struct info)*size, IPC_CREAT | 0777);
if(shm_ID == -1)
{
return -1;
}
info->shm_ID = shm_ID;
int msgID = msgget(key+1, IPC_CREAT | 0666);
info->msgID = msgID;
info->shm_size = size;
return 0;
}
int ringat(ring_t* info, int port)
{
if((port-1) >= 0 && (port-1) <= info->shm_ID)
{
int y;
int id = info->shm_ID;
printf("the shared memory ID is [%i]\n", id);
struct info* i;
i = (struct info*) shmat(id, NULL, 0);
i->port = 55;
printf("the base address is [%p]\n", i);
struct info * ptr = i;
for(y = 0; y<info->shm_size; y++)
{
(ptr+y)->PID = 0;
(ptr+y)->port = 0;
}
info->ptr = i+port-1;
(info->ptr)->port = port;
(info->ptr)->PID = getpid();
printf("The port is [%i] and the PID is [%i] and the pointer address is [%p]\n", (info->ptr)->port, (info->ptr)->PID,(info->ptr));
printf("DONE\n");
return 0;
}
else
{
printf("out of range\n");
return -1;
}
}
【问题讨论】:
-
如果您希望任何人做任何事情但猜测发生了什么,您需要显示一些代码。
-
您应该添加错误检查代码和 perror 错误以消除任何明显的问题。
-
但是没有错误,问题是函数shmat()返回不同的指针指向同一个共享内存
-
正如 Andrew 所指出的,这实际上不是问题。问题是你说变化没有反映在不同的过程中。您从哪里获得“关键”,为每个后续段添加 1?您是否有可能多次附加相同的内存?
-
我在 main 中发送密钥,它是 15,但我试图在消息队列中更改它,希望它能解决问题,因此您可以忽略 msgget() 中的 (key+1)跨度>
标签: c shared-memory