2012-07-22 63 views
2

我嘗試使用共享內存shm_openmmap。但是,每當我嘗試寫入該內存時,都會發生總線錯誤。最簡單的示例代碼如下。這裏有什麼問題,如何解決?嘗試在共享內存中寫入時發生總線錯誤

#include <stdio.h> 
#include <sys/mman.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 

// compile with -lrt 

char fname[64]; 
int fd; 

int main() 
{ 
    int * sm; 
    sprintf(fname, "%d_%u", 4, 4); 

    if ((fd = shm_open(fname, O_CREAT | O_RDWR, 0777)) == -1) 
    {   
     perror(NULL); 
     return 0; 
    } 
    sm = (int*)mmap(0, (size_t)4096, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, 
     fd, 0); 
    printf("Now trying to see if it works!\n"); 
    sm[0] = 42; 
    printf("%d, %d!\n", sm[0], sm[1]); 

    return 0; 
} 

輸出我得到的是以下

Now trying to see if it works! 
Bus error 
+2

你需要檢查'mmap'是否返回'MAP_FAILED',如果是,請參考'errno'來找出原因。 (另外,你不會試圖寫入一個零長度的共享對象,對嗎?mmap'和mmap'區域都不可以放大對象。) – 2012-07-22 13:03:00

+0

相關:http:// stackoverflow.com/questions/212466/what-is-a-bus-error – 2015-08-07 12:03:06

回答

4

新創建的對象有一個大小爲零。您無法通過映射或寫入其映射來更改對象的大小。您可能需要在mmap之前致電ftruncate。 (如果你的代碼有錯誤檢查,這將更容易找出。)

+0

在這種情況下,錯誤檢查並不重要,因爲只要長度是頁面對齊,mmap就會高興地映射零長度文件。 – sergio91pt 2013-04-30 21:07:04

相關問題