是否可以使用 IPC 将 2D 数组分配为共享内存?

发布于 2024-08-16 12:43:53 字数 214 浏览 1 评论 0原文

我想使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

人间不值得 2024-08-23 12:43:53

int** 不是二维数组,而是指针数组。您不应将指针存储在共享内存中,因为共享内存段可能会分配在不同进程中的不同地址处。尝试使用简单、平面的一维数组,它将通过一些索引魔法“模拟”二维数组,即。

x,y -> y*width+x

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.

x,y -> y*width+x
烛影斜 2024-08-23 12:43:53

共享内存中结构的常见做法是存储偏移量而不是指针。这是为了避免内存可能被映射到不同进程中的不同虚拟地址的事实。

另一种常见的方法是让第一个进程请求操作系统提供的映射,然后以某种方式将生成的虚拟地址传递给需要附加到同一内存的所有其他进程,并让它们在该地址请求固定映射。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文