系统相关
首页 > 系统相关> > c – 将写入整数数组读入共享内存

c – 将写入整数数组读入共享内存

作者:互联网

以下是我的共享内存的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;
}

在我尝试读取时写入内存后,输出是垃圾值.有人可以解释我做错了什么(输出显示全部为零)谢谢

解决方法:

在write部分中,在获取共享内存地址后使用了malloc(),因此它将被覆盖.你应该删除malloc()行

在read部分中,for循环应该如下所示

printf("\n%d---\n", array[i] );

标签:c-3,linux,gcc,read-write,shared-memory
来源: https://codeday.me/bug/20190825/1717340.html