2
我嘗試使用共享內存shm_open和mmap。但是,每當我嘗試寫入該內存時,都會發生總線錯誤。最簡單的示例代碼如下。這裏有什麼問題,如何解決?嘗試在共享內存中寫入時發生總線錯誤
#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
你需要檢查'mmap'是否返回'MAP_FAILED',如果是,請參考'errno'來找出原因。 (另外,你不會試圖寫入一個零長度的共享對象,對嗎?mmap'和mmap'區域都不可以放大對象。) – 2012-07-22 13:03:00
相關:http:// stackoverflow.com/questions/212466/what-is-a-bus-error – 2015-08-07 12:03:06