2009年7月14日 星期二

mmap cause Bus error

最近用到Linux 的 mmap 函數 可是卻遇到存取記憶體時發生 Bus error 的問題...
後來在網路上找到相關的文章
原來是因為沒有配置相對應的檔案空間


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

char *name = "/test";
int main(int args, char **argv)
{
char *p;
int f = shm_open(name, O_RDWR|O_CREAT, S_IRWXU);
if ( f < 0 )
{
perror("shm_open() failed.");
exit(1);
}

ftruncate(f, 1024); //少了這行會發生Bus error

p = mmap(0, 1024, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_32BIT, f, 0);
if ( !p )
{
perror("mmap() failed");
exit(1);
}
memcpy(p, name, strlen(name) + 1);
exit(0);
}

來源 http://www.byreach.com/node/314

沒有留言:

張貼留言