使用memcpy和mmap的麻烦

时间:2013-01-09 16:51:27

标签: c 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(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);



}

无法找出问题所在,因为“总线错误”不是描述性错误消息,互联网上没有关于此问题的任何材料。

3 个答案:

答案 0 :(得分:17)

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

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

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

答案 1 :(得分:0)

也许尝试使用memmove?你不是在同一个内存/文件/设备位置读写吗?在这种情况下,Memcpy失败了。

答案 2 :(得分:0)

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