尝试使用这些函数复制文件,一切都很顺利,直到程序遇到memcpy函数,它会产生总线错误并终止进程。
void copy_mmap(char* in, char* out){
int input_fd, output_fd;
input_fd = open (in, O_RDONLY);
if (input_fd == -1) {
printf("Error opening input file.\n");
exit(2);
}
output_fd = open(out, O_RDWR | O_CREAT, S_IWUSR | S_IRUSR);
if(output_fd == -1){
printf("Error opening output file.\n");
exit(3);
}
struct stat st;
fstat(input_fd, &st);
char* target;
target=mmap(0, st.st_size+1, PROT_READ, MAP_SHARED, input_fd, 0);
if (target==(void*) -1){
printf("Error mapping target with errno: %d.\n", errno);
exit(6);
}
char* destination;
destination=mmap(0, st.st_size+1, PROT_READ | PROT_WRITE, MAP_SHARED, output_fd, 0);
if (destination==(void*) -1){
printf("Error mapping destination with errno: %d.\n", errno);
exit(5);
}
memcpy(destination, target, st.st_size);
munmap(destination, st.st_size);
}
无法确定问题出在哪里,因为“总线错误”不是一个描述性的错误消息,并且互联网上关于这个问题的资料非常少。
sendfile
变体。此文件在内核空间中执行整个复制操作(没有数据来回复制到用户空间):http://linux.die.net/man/2/sendfile http://www.freebsd.org/cgi/man.cgi?query=sendfile&sektion=2 https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/sendfile.2.html - panzi