简体   繁体   English

使用memcpy和mmap的麻烦

[英]Troubles with using memcpy with mmap

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



}

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. 将目标文件创建为新文件时,其大小为0字节。 memcpy crashes because it tries to write data beyond the end of the file. memcpy崩溃,因为它试图写入超出文件末尾的数据。

You can make this work by pre-sizing the destination file to the size of the source file (using ftruncate() ) before you mmap() it. 您可以通过在mmap()之前将目标文件预先调整为源文件的大小(使用ftruncate() )来完成此工作。

Also, you should pass st.st_size as the second argument to mmap , not st.st_size+1 . 此外,您应该将st.st_size作为第二个参数传递给mmap ,而不是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. st.st_size+1尝试映射大于文件大小的范围,该范围无效。

Perhaps try to use memmove? 也许尝试使用memmove? Are you not reading and writing from the same memory/file/device location? 你不是在同一个内存/文件/设备位置读写吗? Memcpy fails in such situations. Memcpy在这种情况下失败了。

你也可以lseek到off_t fileposition = lseek(output_fd,st.st_size-1,SEEK_SET)并将一个空字符写入output_fd。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM