Tag Archives: Linux Calls mmap Error

[Solved] Linux Calls mmap Error: mmap: Invalid argument

Background

When using shared memory on Linux, the most common way is to use MMAP mapping file: a few days ago, when writing a program, there was an error in the execution of MMAP:

./test_mmap tmp.txt
mmap: Invalid argument

The procedure is as follows:

#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char **argv)
{
    int fd;
    struct stat sb;
    char *mmapped;

    if (argc != 2) {
        return -1;
    }

    fd = open(argv[1], O_RDWR);
    if(fd < 0) {
        perror("open");
        return -1;
    }

    if(fstat(fd, &sb) == -1) {
        perror("fstat");
        return -1;
    }

    mmapped = mmap(NULL, sb.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    if (mmapped == MAP_FAILED) {
        perror("mmap");
        return -1;
    }

    close(fd);

    mmapped[0] = '1';

    if(msync((void*)mmapped, sb.st_size, MS_SYNC) == -1) {
        perror("msync");
        return -1;
    }

    munmap((void *)mmapped, sb.st_size);

    return 0;
}

I have encountered this problem before, but I forgot what happened and took a little time to find the reason. In order to avoid repeating the mistakes, write an article and record it.

reason

On my environment, the reason for this error is that the mmap mapped file is not on the local machine! My Ubuntu is in a virtual machine, and the host is macOS. A folder on the host is shared to the virtual machine, and it is in this shared folder that the mmap file is in when I execute the program, so this strange error is reported.