2017-10-08 76 views
1

当我尝试写入内存时出现总线错误(核心转储)。我想在Linux中使用mmap()和open()函数写入二进制文件。我想在二进制文件中将1到100的整数映射到内存,而不是直接写入文件。总线错误与mmap

#include <stdio.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 
#include <stdio.h> 
#include <unistd.h> 
#include <sys/mman.h> 
#include <string.h> 
#include <stdlib.h> 
#define FILE_SIZE 0x100 

int main(int argc,char *argv[]) 
{ 

    int fd; 
    void *pmap; 

    printf("im here"); 
    //fd=open(argv[1],O_RDWR|O_CREAT,S_IRUSR|S_IWUSR); 
    fd=open("numbers.raw",O_RDWR); 

    if(fd == -1) 
    { 
     perror("open"); 
     exit(1); 
    } 

    lseek(fd,FILE_SIZE+1,SEEK_SET); //checking the file length 
    lseek(fd,0,SEEK_SET);//points to start of the file 

    //create the memory mapping 
    pmap = mmap(0,FILE_SIZE,PROT_WRITE,MAP_SHARED,fd,0); 



    if(pmap == MAP_FAILED) 
    { 
     perror("mmap") ; 
     close(fd); 
     exit(1); 
    } 

    close(fd); 

    for(int i=1;i<=100;i++) 
     sprintf(pmap,"%d",i); 

    return 0; 

} 

回答

0

你的评论说你是“检查文件长度”,但你永远不会检查该调用的返回值。我敢打赌,它是失败的,因为你的文件不够大,因此后来的总线错误。 有多种其他不相关的错误,在你的文件中,通过 方式:

  1. 你的文件的大小假设为0x100字节,足以存储100个整数二进制。 64位系统并非如此。
  2. 您实际上并不存储二进制数字 - 您正在存储数字的字符串。
  3. 你并没有前进,你写的地方,所以你写在文件的开始,所有的数字,一个在另一个之上。
+0

我已经增加了FILE_SIZE到0xA00在一个更安全的一面。为了存储二进制数字并推进,我使用了printf(pmap,“%d \ n”,i)。但我仍然得到同样的错误。 –

+0

另外如何在open()命令中指定文件大小 –