开始没有区分好匿名内存和文件映射之间的区别,而出现了一些错误。
/********************** > File Name: test_cp.c > Created Time: 2018年03月03日 星期六 09时55分29秒 ****************************/ #ifdef USE_MAP_ANON #define _BSD_SOURCE #endif #include <sys/stat.h> #include <stdio.h> #include <sys/wait.h> #include <sys/mman.h> #include <fcntl.h> #include "tlpi_hdr.h" int main(int argc, char *argv[]) { int *addr, *addr1; int fd,fd1; struct stat sb; fd = open("/home/**/test", O_RDWR); if(fd == -1) errExit("open"); if(fstat(fd, &sb) == -1)//获取文件大小 errExit("fstat"); addr = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd, 0); if(addr == MAP_FAILED) errExit("mmap"); if(close(fd) == -1 ) errExit("close"); fd1 = open("/home/**/cat.txt", O_RDWR | O_CREAT | O_TRUNC); if(fd1 == -1) errExit("open"); if( ftruncate(fd1, sb.st_size)== -1) errExit("ftruncate"); addr1 = mmap(NULL, sb.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd1, 0); if(addr1 == MAP_FAILED) errExit("mmap"); memcpy(addr1, addr, sb.st_size); return(EXIT_SUCCESS); }