使用memcpy和mmap的麻烦

使用memcpy和mmap的麻烦,第1张

概述尝试使用这些函数复制文件,一切顺利,直到程序到达memcpy函数,这会产生总线错误并终止进程.void copy_mmap(char* in, char* out){ int input_fd, output_fd; input_fd = open (in, O_RDONLY); if (input_fd == -1) { printf(

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

总结

以上是内存溢出为你收集整理的使用memcpy和mmap的麻烦全部内容,希望文章能够帮你解决使用memcpy和mmap的麻烦所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/1047278.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存