总线错误打开和mmap的文件 [英] Bus error opening and mmap'ing a file

查看:192
本文介绍了总线错误打开和mmap的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个文件并将其映射到内存中。我认为我的代码将工作,但是当我运行它时,我得到一个总线错误。我搜索谷歌,但我不知道如何解决这个问题。这里是我的代码:

I want to create a file and map it into memory. I think that my code will work but when I run it I'm getting a "bus error". I searched google but I'm not sure how to fix the problem. Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/mman.h>
#include <string.h>

int main(void)
{
    int file_fd,page_size;
    char buffer[10]="perfect";
    char *map;

    file_fd=open("/tmp/test.txt",O_RDWR | O_CREAT | O_TRUNC ,(mode_t)0600);

    if(file_fd == -1)
    {
        perror("open");
        return 2;
    }

    page_size = getpagesize();

    map = mmap(0,page_size,PROT_READ | PROT_WRITE,MAP_SHARED,file_fd,page_size);

    if(map == MAP_FAILED)
    {
        perror("mmap");
        return 3;
    }

    strcpy(map, buffer);

    munmap(map, page_size);
    close(file_fd);
    return 0;
}


推荐答案

大小的文件,您不能用mmap扩展文件大小。当您尝试在文件的内容之外写入时,会出现总线错误。

You are creating a new zero sized file, you can't extend the file size with mmap. You'll get a bus error when you try to write outside the content of the file.

使用例如在文件描述符上 fallocate ()分配文件中的空间。

Use e.g. fallocate() on the file descriptor to allocate room in the file.

请注意,您也将page_size作为偏移量传递给mmap,这在您的示例中似乎没有多大意义,您必须首先扩展如果要在该位置写 buf ,则将文件保存到 pagesize + strlen(buffer)+ 1 更有可能你想从文件的开头开始,所以传递0作为mmap的最后一个参数。

Note that you're also passing the page_size as the offset to mmap, which doesn't seem to make much sense in your example, you'll have to first extend the file to pagesize + strlen(buffer) + 1 if you want to write buf at that location. More likely you want to start at the beginning of the file, so pass 0 as the last argument to mmap.

这篇关于总线错误打开和mmap的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆