tcjsea 发表于 2013-05-05 12:03

bus error mmap

各位大侠,小弟最近在学习linux下的编程,在进行一个mmap实验程序的时候,出现了bus error这个错误,百思不得其解,望各位大侠指教:
// receiver.c

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

const int SIZE = 100;

void main() {
   int i;
   int fd = open("./block", O_RDWR, 0666);
   if(fd < 0) {
      perror("open failed");
      return;
   }

   //Now map this file to memory
   caddr_t addr = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
   if(addr <= 0) {
      perror("mmap failed");
      return;
   }

printf("%s\n",addr);
}
注:这个程序刚开始运行时还好好的,后来改了一下,出现错误,又改回来,就出现bus error了!
运行环境:virtualbox 上的ubuntu13.04

linux_c_py_php 发表于 2013-05-05 12:56

文件有那么大吗

tcjsea 发表于 2013-05-05 14:20

不是,仅仅是做个试验,用mmap实现两个进程的通信!

bzcat 发表于 2013-05-05 17:14

加上ftruncate(fd,SIZE);

tcjsea 发表于 2013-05-05 21:32

好的,非常感谢,果然可以。不过还想请教一下,这是什么原因呢,我在网上查,bus error多半是未对齐的原因,那么这里是不是这个原因呢?

井蛙夏虫 发表于 2013-05-05 23:12

本帖最后由 井蛙夏虫 于 2013-05-05 23:14 编辑

man mmap只说了一种导致SIGBUS的情况:
"Use of a mapped region can result in these signals:
SIGBUS:Attempted access to a portion of the buffer that does not correspond to the file."
可能是你的文件太小了,不足SIZE大小,printf调用访问时导致SIGBUS。

apue中程序14-12的注释也说明了这种情况。

tcjsea 发表于 2013-05-06 21:44

恩,好的,收益匪浅,谢谢了!
页: [1]
查看完整版本: bus error mmap