【发布时间】:2014-01-20 06:08:41
【问题描述】:
以下是我的共享内存的 READER-WRITER 代码。
阅读代码-
int main(){
int shmid;
int *array;
int count = 5;
int i = 0;
key_t key = 12345;
shmid = shmget(key, count*sizeof(int), IPC_EXCL);
array = shmat(shmid, 0, SHM_RDONLY);
for(i=0; i<5; i++)
{
printf("\n%d---\n", array[i] );
}
printf("\nRead to memory succesful--\n");
shmdt((void *) array);
return 0;
}
编写代码-
int main()
{
int shmid;
int *array;
int count = 5;
int i = 0;
int SizeMem;
key_t key = 12345;
SizeMem = sizeof(*array)*count;
shmid = shmget(key, count*sizeof(int), IPC_CREAT);
array = (int *)shmat(shmid, 0, 0);
array = malloc(sizeof(int)*count);
for(i=0; i<5; i++)
{
array[i] = i;
}
for(i=0; i<count; i++)
{
printf("\n%d---\n", array[i]);
}
printf("\nWritting to memory succesful--\n");
shmdt((void *) array);
return 0;
}
当我尝试读取时写入内存后,输出是垃圾值。谁能解释一下我做错了什么(输出显示全为零)谢谢
【问题讨论】:
-
在写入部分,您将使用 malloc 的返回地址覆盖数组指针并写入堆分配而不是共享内存。 malloc 是不必要的。
-
从 shmat 获取值后,您正在 malloc'ing 数组。有效地摆脱价值观。
-
@AnshDavid 测试了您的代码,删除了我在回答中提到的行,它在我的机器上运行正常。我应该没问题。
标签: c linux gcc shared-memory read-write