gpt4 book ai didi

c - mmap SIGBUS 错误和初始化文件

转载 作者:太空狗 更新时间:2023-10-29 16:05:42 26 4
gpt4 key购买 nike

我正在尝试通过映射一个 1 MiB 文件(与 RAM 大小相对应)来为基本 CPU 建模。我想读/写这个文件。目前,我收到 ram[2] = 1 的 SIGBUS 错误,我收集到这是由于尝试在文件范围之外进行 mmap。我读过,也许我需要用零作为占位符来填充文件,但我对为什么必须这样做感到有点困惑,因为我认为 mmap 会自动为我预留一个内存块来分配当我第一次触摸它时(正如我在下面的测试中尝试做的那样)。我错过了什么?

int16_t ramD;
if ( (ramD = open("ramMap.txt", O_RDWR | O_CREAT, 0666)) == -1)
{
errx(EX_OSERR, "RAM could not be initialized");
}

uint8_t* ram = mmap(0, ram_bytes, PROT_READ | PROT_WRITE, MAP_SHARED, ramD, 0);

ram[2] = 1;
printf("%i", ram[2]);

最佳答案

SIGBUS 表示您正在文件外写入。来自 Linux 手册页 mmap(2) :

SIGBUS

Attempted access to a portion of the buffer that does not correspond to the file (for example, beyond the end of the file, including the case where another process has truncated the file).

当您创建一个新文件时,它最初是空的,即大小为 0 字节。您需要使用 ftruncate 调整它的大小,使其至少足以包含写入的地址(可能四舍五入到页面大小)。因为你想要一个大小为 ram_bytes 的 ram 磁盘,那么:

ftruncate(ramD, ram_bytes);

See this answer for a longer explanation about the same mechanism, using POSIX shared memory objects .


附言。 open 返回一个 int;您应该使用 int 而不是 int16_t 来存储文件描述符。

关于c - mmap SIGBUS 错误和初始化文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44553907/

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