代码之家  ›  专栏  ›  技术社区  ›  lrleon

mmap内存区域出现总线错误

  •  2
  • lrleon  · 技术社区  · 8 年前

    在以下简单程序中:

    # include <sys/mman.h>
    # include <fcntl.h>
    # include <cstdlib>
    
    # include <cassert>
    
    struct rgn_desc
    {
      size_t end_;
      char data[];
    };
    
    int main(int argc, const char *argv[])
    {
      int fd = open("foo.mm", O_RDWR|O_CREAT|O_TRUNC, (mode_t)0700);
    
      assert(fd != -1);
    
      void * ptr = mmap(NULL, 4096, PROT_READ | PROT_WRITE,
                        MAP_SHARED | MAP_POPULATE, fd, 0);
    
      assert(ptr != (void*) -1);
    
      rgn_desc * rgn_ptr = (rgn_desc*) ptr;
      rgn_ptr->end_ = 0; // <-- bus error
    }
    

    基本上,我想管理一个简单的mmaped竞技场分配器,并将其存储为映射我分配的字节的第一部分。所以,当我从一个文件中恢复时,我得到了分配的字节数。

    不过,最后一句话是 bus error .有人能解释为什么,如果可能的话,给我一个避免的方法吗?我在32位Pentium上运行Linux,并使用clang++编译器

    1 回复  |  直到 8 年前
        1
  •  2
  •   Stargateur    8 年前

    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).
    

    在你剪下的文件中,你的文件大小与你的不匹配。 mmap() ftruncate()

    ftruncate(fd, 4096);