【问题标题】:Writing to a memory mapped file shows read accesses in htop写入内存映射文件显示 htop 中的读取访问
【发布时间】:2021-10-27 10:02:16
【问题描述】:

我想使用内存映射文件来写入数据。我在 ubuntu 机器上使用以下测试代码。代码用g++ -std=c++14 -O3编译。

#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstdlib>
#include <cstdio>
#include <cassert>

int main(){
    constexpr size_t GB1 = 1 << 30;

    size_t capacity = GB1 * 4;
    size_t numElements = capacity / sizeof(size_t);

    int fd = open("./mmapfile", O_RDWR);
    assert(fd >= 0);

    int error = ftruncate(fd, capacity);
    assert(error == 0);

    void* ptr = mmap(0, capacity, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    assert(ptr != MAP_FAILED);

    size_t* data = (size_t*)ptr;

    for(size_t i = 0; i < numElements; i++){
        data[i] = i;
    }

    munmap(ptr, capacity);
}

数据正在正确写入文件。但是,htop 命令显示程序的磁盘 io 带宽的一半被读取访问使用。我担心的是,如果只有一半的带宽可以用于写入,代码将无法正常运行。

为什么代码中有读访问? 可以避免还是可以预期?

【问题讨论】:

  • 开始之前文件是空的吗?如果你用O_TRUNC打开来删除文件之前的内容怎么办?然后你的ftruncate 应该使它成为一个完全稀疏的文件,没有任何东西可以从磁盘读取来填充错误的页面。

标签: c++ c linux mmap


【解决方案1】:

发生读取访问是因为第一次访问页面时需要从磁盘读取它们。操作系统不是透明的,也不知道读取会被丢弃。

为避免此问题,请勿使用mmap()。在缓冲区中构建块并以老式方式将它们写出来。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多