当前位置: 技术问答>linux和unix
一个简单的内存映象I/O问题
来源: 互联网 发布时间:2016-01-31
本文导语: 我的代码如下: #include #include #include #include #include #include #include #include #include int main(void) { int outfile; char *mapped; char *ptr; if(outfile=open("test.dat", O_RDWR | ...
我的代码如下:
#include
#include
#include
#include
#include
#include
#include
#include
#include
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,"",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: %dn",atoi(mapped)*2);
//msync(mapped,1000,MS_SYNC);
munmap(mapped,1000);
return 0;
}
编译通过,但是执行时老是在更改内存(*ptr='z';或memcpy(ptr,"test",9);)时报错,说“段错误”,谁能告诉我为什么啊?
#include
#include
#include
#include
#include
#include
#include
#include
#include
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,"",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: %dn",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)
就可以了.赋值运算符的优先级最低.
这的问题.
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)
就可以了.赋值运算符的优先级最低.
这个家伙看问题很细啊.
这的问题.
if((outfile=open("test.dat", O_RDWR | O_CREAT | O_TRUNC,0640))==-1)
就可以了.赋值运算符的优先级最低.
这个家伙看问题很细啊.