一个简单的内存映象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_RDWR | O_CREAT | O_TRUNC,0640)==-1)
这的问题.
if((outfile=open( "test.dat ", O_RDWR | O_CREAT | O_TRUNC,0640))==-1)
就可以了.赋值运算符的优先级最低.
[解决办法]
ptr指向的是一个常量,只能被读不能被写,有段保护机制
[解决办法]
if(outfile=open( "test.dat ", O_RDWR | O_CREAT | O_TRUNC,0640)==-1)
这的问题.
if((outfile=open( "test.dat ", O_RDWR | O_CREAT | O_TRUNC,0640))==-1)
就可以了.赋值运算符的优先级最低.
这个家伙看问题很细啊.