使用memcpy和mmap的麻烦

前端之家收集整理的这篇文章主要介绍了使用memcpy和mmap的麻烦前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

尝试使用这些函数复制文件,一切顺利,直到程序到达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,PROT_READ | PROT_WRITE,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);



}

无法弄清楚出现了什么问题,因为“总线错误”不是描述性错误消息,互联网上没有关于此问题的任何材料.

最佳答案
将目标文件创建为新文件时,其大小为0字节. memcpy崩溃,因为它试图写入超出文件末尾的数据.

您可以通过在mmap()之前将目标文件预先调整为源文件的大小(使用ftruncate())来完成此工作.

此外,您应该将st.st_size作为第二个参数传递给mmap,而不是st.st_size 1. st.st_size 1尝试映射大于文件大小的范围,该范围无效.

原文链接:https://www.f2er.com/linux/440574.html

猜你在找的Linux相关文章