2017-10-08 77 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()命令中指定文件大小 –