是否可以使用 IPC 将 2D 数组分配为共享内存?
我想使用 IPC 将共享内存分配为 2D 数组。我尝试了以下操作:
id_shmem = shmget(ipc_key, sizeof(int)*rows*columns, IPC_CREAT|0666);
matrix = (int **)shmat(id_shmem, 0, 0);
问题是,每当我尝试将某些内容写入矩阵时,都会出现段错误。
I want to allocate shared memory as a 2D array using IPC. I tried the following:
id_shmem = shmget(ipc_key, sizeof(int)*rows*columns, IPC_CREAT|0666);
matrix = (int **)shmat(id_shmem, 0, 0);
The problem is that whenever I try to write something into the matrix, I get a segment fault.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
int** 不是二维数组,而是指针数组。您不应将指针存储在共享内存中,因为共享内存段可能会分配在不同进程中的不同地址处。尝试使用简单、平面的一维数组,它将通过一些索引魔法“模拟”二维数组,即。
int** is not 2D array, it is rather an array of pointers. You should not store pointers in shared memory, as shared memory segment may be allocated at different addresses in different processes. Try to use simple, flat 1D array, which will "emulate" 2D array with some index magic, ie.
共享内存中结构的常见做法是存储偏移量而不是指针。这是为了避免内存可能被映射到不同进程中的不同虚拟地址的事实。
另一种常见的方法是让第一个进程请求操作系统提供的映射,然后以某种方式将生成的虚拟地址传递给需要附加到同一内存的所有其他进程,并让它们在该地址请求固定映射。
Common practice with structures in shared memory is storing offsets and not pointers. This is to get around the fact that memory could be mapped at different virtual addresses in different processes.
Another common approach is to let first process request OS-provided mapping and then somehow pass the resulting virtual address to all other processes that need to be attached to the same memory, and have them request fixed mapping at that address.