mmap SIGBUS错误并初始化文件 [英] mmap SIGBUS error and initializing the file
问题描述
我试图通过映射1个MiB文件(与RAM大小相对应)来对基本CPU进行建模.我想读/写这个文件.目前,我收到ram[2] = 1
的SIGBUS错误,该错误是由于尝试在文件范围之外进行mmap而引起的.我读过,也许我需要用零填充文件作为占位符,但是我为什么必须这样做有点困惑,因为我认为mmap会自动为我分配一个内存块,该内存块将被分配当我第一次触摸它时(因为我正尝试在下面进行测试).我想念什么?
I'm trying to model a basic CPU by mmapping a 1 MiB file, corresponding to the RAM size. I want to read/write this file. Currently I'm getting a SIGBUS error with ram[2] = 1
which I gather is from trying to mmap outside the file range. I've read that perhaps I need to fill the file with zeroes as placeholders, but I'm a bit confused as to why I have to do this, since I thought mmap would automatically set aside a memory chunk for me that would be allocated when I first touch it (as I am trying to do below with my test). What am I missing?
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)
:
The SIGBUS
means that you're writing outside the file. From Linux man pages mmap(2)
:
SIGBUS
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).
在创建新文件时,它最初是 empty ,即大小为0个字节.您需要使用ftruncate
调整其大小,使其至少足以容纳写入的地址(可能舍入为页面大小).如果您想要一个大小为ram_bytes
的ram磁盘,则:
As you create a new file, it is initially empty, i.e. has size of 0 bytes. You need to resize it using ftruncate
to be at least big enough to contain the address written to (possibly rounded up to the page size). As you wanted to have a ram disk of size ram_bytes
, then:
ftruncate(ramD, ram_bytes);
有关使用POSIX共享内存对象的相同机制的详细说明,请参见此答案.
PS. open
返回int
;您应该使用int
而不是int16_t
来存储文件描述符.
PS. open
returns an int
; you should use an int
, not int16_t
, to store the file descriptor.
这篇关于mmap SIGBUS错误并初始化文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!