尝试使用这些函数复制文件,一切顺利,直到程序到达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);
}
Run Code Online (Sandbox Code Playgroud)
无法弄清楚出现了什么问题,因为"总线错误"不是描述性错误消息,互联网上没有关于此问题的任何材料.
Cel*_*ada 18
将目标文件创建为新文件时,其大小为0字节.memcpy崩溃,因为它试图写入超出文件末尾的数据.
您可以通过在将目标文件大小调整为源文件(使用ftruncate())之前将其大小调整来完成此工作mmap().
此外,您应该st.st_size作为第二个参数传递给mmap,而不是st.st_size+1.st.st_size+1尝试映射大于文件大小的范围,该范围无效.
| 归档时间: |
|
| 查看次数: |
5962 次 |
| 最近记录: |