总线错误打开和mmap的文件

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

#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,这在您的示例中似乎没有多大意义,如果您希望将文件扩展到pagesize + strlen(buffer) + 1 ,在该位置写buf 。 更可能的是你想从文件的开头开始,所以传递0作为mmap的最后一个参数。