user318904
user318904

Reputation: 3076

using mmap to copy a file

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?

Upvotes: 2

Views: 2234

Answers (1)

Damon
Damon

Reputation: 70206

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).

Upvotes: 3

Related Questions