以下是我的共享内存的读写代码。
阅读代码-
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()
行
在读取部分,for循环应该是这样的
printf("\n%d---\n", array[i] );
关于c - 读写整数数组到共享内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21227270/