linux – 总线错误打开和mmap’ing文件
发布时间:2020-05-23 15:34:45 所属栏目:Linux 来源:互联网
导读:我想创建一个文件并将其映射到内存中.我认为我的代码可以工作,但是当我运行它时,我得到一个“总线错误”.我搜索谷歌,但我不知道如何解决问题.这是我的代码: #include stdio.h#include stdlib.h#include fcntl.h#include errno.h#include sys/types.h#include
|
我想创建一个文件并将其映射到内存中.我认为我的代码可以工作,但是当我运行它时,我得到一个“总线错误”.我搜索谷歌,但我不知道如何解决问题.这是我的代码: #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扩展文件大小.当您尝试在文件内容之外写入时,您将收到总线错误.使用例如fallocate()在文件描述符上分配文件中的空间. 请注意,您还将page_size作为偏移量传递给mmap,这在您的示例中似乎没有多大意义,如果要编写buf,则必须先将文件扩展到pagesize strlen(buffer)1在那个位置.您更希望从文件的开头开始,因此将0作为mmap的最后一个参数传递. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
