加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

使用memcpy和mmap的麻烦

发布时间:2020-12-13 19:12:11 所属栏目:Linux 来源:网络整理
导读:尝试使用这些函数复制文件,一切顺利,直到程序到达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(

尝试使用这些函数复制文件,一切顺利,直到程序到达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尝试映射大于文件大小的范围,该范围无效.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读