使用 mmap 复制文件
是否可以将源文件映射到目标文件的映射区域,作为将源复制到目标的方法?我尝试了一个简单的实现(如下),但它不起作用。
int main(int argc, char *argv[])
{
struct stat ss;
int src = open(argv[1], O_RDONLY);
fstat(src, &ss);
int dest = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, ss.st_mode);
void *dest_addr = mmap(NULL, ss.st_size, PROT_WRITE, MAP_SHARED, dest, 0);
printf("dest is: %x\n", dest_addr);
void *src_addr = mmap(dest_addr, ss.st_size, PROT_READ, MAP_PRIVATE | MAP_FIXED, src, 0);
printf("src is: %x\n", src_addr);
if (munmap(dest_addr, ss.st_size))
printf("munmap failed");
if (munmap(src_addr, ss.st_size))
printf("munmap failed");
}
上面将源“映射”到目标 mmap,但这并没有按照希望的方式到达实际文件。我只是太天真了吗?
Is it possible to mmap a source file over the mmaped region of a destination file as a means of copying source to destination? I have tried a straightforward implementation (below) but it does not work..
int main(int argc, char *argv[])
{
struct stat ss;
int src = open(argv[1], O_RDONLY);
fstat(src, &ss);
int dest = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, ss.st_mode);
void *dest_addr = mmap(NULL, ss.st_size, PROT_WRITE, MAP_SHARED, dest, 0);
printf("dest is: %x\n", dest_addr);
void *src_addr = mmap(dest_addr, ss.st_size, PROT_READ, MAP_PRIVATE | MAP_FIXED, src, 0);
printf("src is: %x\n", src_addr);
if (munmap(dest_addr, ss.st_size))
printf("munmap failed");
if (munmap(src_addr, ss.st_size))
printf("munmap failed");
}
The above maps the source "over" the destination mmap, but the this does not make its way down to the actual file as hoped. Am I just being naive?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将两个文件映射到同一内存区域是有问题的。该内存的内容应该是什么,来自第一个文件或第二个文件的数据,还是混合的数据?这行不通。
您可以做的是将两个文件和 memcpy 从一个映射区域映射到另一个区域。但请注意,最好先创建文件并设置其长度,否则
mmap
可能会返回SIGBUS
(请参阅文档)。Mapping two files to the same memory region is problematic. What should the contents of this memory be, data from the first file or the second, or a mix? This won't work.
What you can do is map two files and
memcpy
from one mapped region to the other. Note, however, that it is a good idea to create the file first and set its length, otherwisemmap
may returnSIGBUS
(see docs).