我有以下代码(更新):
#include <iostream>
#include <cassert>
#include <errno.h>
#include <string.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <new>
struct S {
uint32_t a;
uint32_t b;
};
int main() {
const auto fd = open("/tmp/abc.txt", O_RDWR | O_CREAT, S_IRWXU);
assert(fd > 0);
void* ptr = mmap(nullptr, sizeof(S), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
assert(MAP_FAILED != ptr);
std::cout << "address: " << ptr << std::endl;
auto tptr = new (ptr) S();
tptr->a = 99;
const auto rc = msync(&ptr, sizeof(S), MS_ASYNC);
std::cout << "msync returned " << rc << std::endl;
if (rc != 0) {
std::cout << "error code = " << errno << ": " << strerror(errno) << std::endl;
}
}当我在GDB运行它时,我得到了这个:
address: 0x7ffff7ff8000
Program received signal SIGBUS, Bus error.
0x0000000000400adb in main () at msync.cpp:20
20 auto tptr = new (ptr) S();我看到一些人提到了内存对齐问题,我检查了0x7ff7ff7ff8000是否可以被2、8、16、32和64整除。然后,我感到困惑的是,它所期待的是什么样的一致。或者是别的什么?
提前谢谢。
发布于 2018-02-08 08:04:07
您似乎正在尝试在这里创建文件并将其写入其中,因此最初它的大小为零,占用的内存页为零。但是mmap不能在文件结束后编写,从而有效地为您分配内存:首先,它如何知道要向文件中添加多少字节?您需要确保/tmp/abc.txt包含一些字符,这些字符随后可以被布局new覆盖。它不能附加。
在我将大约8个随机字节写入/tmp/abc.txt之后运行您的程序,并通过
63 00 00 00 00 00 00 00就像我的x86-64预期的那样。然后,该程序报告您可能要生成的msync错误,并优雅地退出。
https://stackoverflow.com/questions/48680215
复制相似问题