日期:2014-05-16  浏览次数:20619 次

一个简单的内存映象I/O问题
我的代码如下:
#include   <sys/types.h>
#include   <sys/stat.h>
#include   <sys/mman.h>
#include   <stdio.h>
#include   <string.h>
#include   <stdlib.h>
#include   <errno.h>
#include   <unistd.h>
#include   <fcntl.h>

int   main(void)
{
                int   outfile;
                char   *mapped;
                char   *ptr;
                if(outfile=open( "test.dat ",   O_RDWR   |   O_CREAT   |   O_TRUNC,0640)==-1)
                {
                                printf( "couldn 't   open   the   file.\n ");
                                exit(254);
                }
                lseek(outfile,1000,SEEK_SET);
                if(write(outfile, "\0 ",1)==-1)
                {
                                printf( "couldn 't   write   into   file ");
                                exit(254);
                }
                mapped=(char   *)mmap(NULL,1000,   PROT_READ   |   PROT_WRITE,   MAP_SHARED,   outfile,0);
                if(!mapped)
                {
                                printf( "Map   failed ");
                }
                close(outfile);
                ptr=mapped;
                printf( "PLEASE   ENTER   A   NUMBER: ");
                *ptr= 'z ';
                //memcpy(ptr, "test ",9);
                //ptr+=mapped;
                //printf( "your   number   times   two   is:   %d\n ",atoi(mapped)*2);
                //msync(mapped,1000,MS_SYNC);
                munmap(mapped,1000);
                return   0;
}
编译通过,但是执行时老是在更改内存(*ptr= 'z ';或memcpy(ptr, "test ",9);)时报错,说“段错误”,谁能告诉我为什么啊?

------解决方案--------------------
if(outfile=open( "test.dat ", O