红联Linux门户
Linux帮助

使用mmap函数,不知为何会segmentation fault,

发布时间:2010-02-08 11:26:28来源:红联作者:chhaya
[code]#include
#include
#include
#include
#include
#include

int main()
{
int fd;
if ( (fd = open("./file", O_RDWR|O_CREAT, S_IRWXU)) < 0){
printf("open file wrong!");
exit(1);
}

struct stat file_stat;
if ( fstat( fd, &file_stat) < 0 )
{
printf(" fstat wrong");
exit(1);
}



void *start_fp;
if( ( start_fp = mmap(NULL, file_stat.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0 )) == MAP_FAILED)
{
printf("mmap wrong");
exit(0);
}

snprintf( (char *)start_fp, 4, "test"); //不知道这里为何段错误,有时候还总线错误
msync( start_fp, file_stat.st_size, MS_ASYNC);

if ( munmap( start_fp, file_stat.st_size ) < 0 )
{
printf("munmap wrong");
exit(1);
}
}[/code]
文章评论

共有 1 条评论

  1. piaoyun1979 于 2010-03-15 22:33:12发表:

    把start_fp的值打出来看看不就知道了吗