如何将 shmat 与非 NULL 页面对齐的 shmaddr 一起使用?

How to use shmat with non-NULL page-aligned shmaddr?

本文关键字:shmaddr 一起 对齐 面对 shmat 与非 NULL      更新时间:2023-10-16

>我正在尝试使用堆创建的变量的地址创建共享内存,我确保地址与页面对齐,但仍然收到错误:"无效参数"。我怎样才能正确地做到这一点?

#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <cstdint>
const int PERMISSION = 0666; //-rw-rw-rw-
int main() {
int size = 10;
void* testp = std::aligned_alloc(SHMLBA, size);
int shkey = 314159, shmid;
if ((shmid = shmget(shkey, size, IPC_CREAT | PERMISSION)) == -1) {
perror("shmget: shmget failed");
exit(-1);
}
void *ret;
if ((ret = shmat(shmid, testp, 0)) == (void*)-1) {
perror("shmat: shmat failed");
exit(-1);
}
return 0;
}

C++17 标准说,如此处所述,

传递size不是对齐的整数倍或 实现无效或不支持的对齐方式 导致函数失败并返回空指针(C11,如 已发布,在这种情况下指定未定义的行为,这是 由DR 460更正)。

那么什么是SHMLBA?它应该是一个整体,正如所说,是对齐的一个因素。

在使用非 NULL 参数调用shmat时,似乎必须传递SHM_REMAP

shmat (shmid, testp, SHM_REMAP);

为什么会这样还不是很明显。 根据文档,此标志是特定于 Linux 的。

现场演示