- 论坛徽章:
- 0
|
20可用积分
用mmap映射两个文件,然后把一个文件的内容复制到另一个文件
采用的是memcpy函数
但是使用这个函数出现了总线错误
我把两个映射的地址和长度都输出来了
请高手给分析一下。
输出结果:
file size = 18
src = 0xb7fa9000
dst = 0xb7fa8000
总线错误
- #include <stdio.h>
- #include <fcntl.h>
- #include <sys/mman.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <stdlib.h>
- #include <string.h>
- int main(int argc,char *argv[])
- {
- int fdin,fdout;
- void *src,*dst;
- struct stat statbuf;
- if(argc != 3)
- {
- printf("usage : %s <fromfile> <tofile>\n",argv[0]);
- return 1;
- }
- if((fdin = open(argv[1],O_RDONLY)) == -1)
- {
- printf("can't open file %s\n",argv[1]);
- return 1;
- }
- if((fdout = open(argv[2],O_RDWR | O_CREAT | O_TRUNC,0644)) == -1)
- {
- printf("can't create file %s\n",argv[2]);
- return 1;
- }
- if(fstat(fdin,&statbuf) < 0)
- {
- printf("fstat error.\n");
- return 1;
- }
- printf("file size = %d\n",statbuf.st_size);
- if(lseek(fdout,statbuf.st_size - 1,SEEK_SET) == -1)
- {
- printf("set file size error.\n");
- return 1;
- }
- printf("file size = %d\n",statbuf.st_size);
- if(lseek(fdout,statbuf.st_size - 1,SEEK_SET) == -1)
- {
- printf("set file size error.\n");
- return 1;
- }
- if((src = mmap(0,statbuf.st_size,PROT_READ,MAP_SHARED,fdin,0)) == MAP_FAILED)
- {
- printf("mmap error for fdin.\n");
- return 1;
- }
- printf("src = 0x%x\n",src);
- if((dst = mmap(0,statbuf.st_size,PROT_READ | PROT_WRITE,MAP_SHARED,fdout,0)) == MAP_FAILED)
- {
- printf("mmap error for fdout.\n");
- return 1;
- }
- printf("dst = 0x%x\n",dst);
- memcpy(dst,src,statbuf.st_size);
- close(fdin);
- close(fdout);
- exit(0);
- }
复制代码 |
最佳答案
查看完整内容
可以正常工作的代码类似:一种输出:[lgr@localhost Lab]$ ./a.out mmap.c out.cPageSize: 4096filein size = 1568fileout size = 1568LZ出Bus Error的原因:1,lseek只是改变文件偏移量,不是文件实际大小,用ls -l就可以明显看到两个文件的区别。可以先通过lseek到文件尾,再write一个字节来改变输出文件的大小或者直接使用ftruncate。2,内核很清楚被映射的对象大小(你的输出文件大小为0),而内存映射区域总是以页为单位(如4 ...
|