gpt4 book ai didi

c - 读写整数数组到共享内存

转载 作者:可可西里 更新时间:2023-11-01 11:46:17 25 4
gpt4 key购买 nike

以下是我的共享内存的读写代码。

阅读代码-

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com