使用 mmap 复制文件

发布于 2024-11-25 18:22:17 字数 735 浏览 4 评论 0原文

是否可以将源文件映射到目标文件的映射区域,作为将源复制到目标的方法?我尝试了一个简单的实现(如下),但它不起作用。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人疚 2024-12-02 18:22:17

将两个文件映射到同一内存区域是有问题的。该内存的内容应该是什么,来自第一个文件或第二个文件的数据,还是混合的数据?这行不通。

您可以做的是将两个文件和 memcpy 从一个映射区域映射到另一个区域。但请注意,最好先创建文件并设置其长度,否则 mmap 可能会返回 SIGBUS (请参阅文档)。

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, otherwise mmap may return SIGBUS (see docs).

SIGBUS Attempted access to a portion of the buffer that does not
correspond to the file (for example, beyond the end of the file,
including the case where another process has truncated the file).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文