- 论坛徽章:
- 0
|
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <assert.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <sys/mman.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- int main(int argc,char *argv[])
- {
- int fdin,fdout;
- void *src,*dst;
- size_t pagesize;
- struct stat statbuf;
- if(argc != 3)
- {
- printf("usage : %s <fromfile> <tofile>\n",argv[0]);
- return 1;
- }
- pagesize = sysconf(_SC_PAGESIZE);
- printf("PageSize: %ld\n", (long)pagesize);
- 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;
- }
- assert(fstat(fdin,&statbuf) == 0);
- printf("filein size = %ld\n",statbuf.st_size);
- assert(ftruncate(fdout, statbuf.st_size) == 0
- && fstat(fdout, &statbuf) == 0);
- printf("fileout size = %ld\n",statbuf.st_size);
- src = mmap(0,statbuf.st_size,PROT_READ,MAP_SHARED,fdin,0);
- if( src == MAP_FAILED )
- {
- printf("mmap error for fdin.\n");
- return 1;
- }
- dst = mmap(0,statbuf.st_size,PROT_READ | PROT_WRITE,MAP_SHARED,fdout,0);
- if( dst == MAP_FAILED )
- {
- printf("mmap error for fdout.\n");
- return 1;
- }
- memcpy(dst,src,statbuf.st_size);
- close(fdin);
- close(fdout);
- return 0;
- }
复制代码
貌似有点懂了,
lseek了一个空洞 如果没write,也就是说如果lseek之后没有发生i/o操作时,lseek只是把偏移量给改了一下
并没有在磁盘上分配存储区
而你的文件是新建的 存储的空间长度为0 lseek之后还是为0
把mmap到系统的线性地址空间,然后进行复制的话就会出错。 |
|