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