使用memcpy和mmap的麻烦 [英] Troubles with using memcpy with mmap

查看:138
本文介绍了使用memcpy和mmap的麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用这些功能复制文件,一切正常,直到程序运行memcpy函数,这会导致总线错误并终止进程.

  void copy_mmap(char * in,char * out){int input_fd,output_fd;input_fd =打开(在O_RDONLY中);如果(input_fd == -1){printf(打开输入文件时出错.\ n");出口(2);}output_fd = open(out,O_RDWR | O_CREAT,S_IWUSR | S_IRUSR);if(output_fd == -1){printf(打开输出文件时出错.\ n");出口(3);}struct stat st;fstat(input_fd,& st);char *目标;target = mmap(0,st.st_size + 1,PROT_READ,MAP_SHARED,input_fd,0);如果(target ==(void *)-1){printf(使用errno映射错误的目标:%d.\ n",errno);退出(6);}char *目的地;destination = mmap(0,st.st_size + 1,PROT_READ | PROT_WRITE,MAP_SHARED,output_fd,0);如果(目标==(无效*)-1){printf(错误映射目标为errno:%d.\ n",errno);出口(5);}memcpy(目的地,目标,st_st_size);munmap(目的地,st.st_size);} 

由于"Bus Error"不是描述性的错误消息,并且在互联网上也没有太多有关此问题的资料,因此无法弄清问题所在.

解决方案

将目标文件创建为新文件时,其大小为0字节. memcpy 崩溃,因为它试图在文件末尾写入数据.

您可以通过在 mmap()之前将目标文件调整为源文件的大小(使用 ftruncate())来实现此目的./p>

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

Trying to copy a file using these functions, everything goes fine until program hits the memcpy function which gives a bus error and terminates the process.

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);



}

Failed to figure out what is wrong, as "Bus Error" isn't a descriptive error message and there isn't any much material on the internet regarding this problem.

解决方案

When you create the destination file as a new file, its size is 0 bytes. memcpy crashes because it tries to write data beyond the end of the file.

You can make this work by pre-sizing the destination file to the size of the source file (using ftruncate()) before you mmap() it.

Also, you should pass st.st_size as the second argument to mmap, not st.st_size+1. st.st_size+1 tries to map a range that is larger than the size of the file, which is invalid.

这篇关于使用memcpy和mmap的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆