Search code examples
pythoncmmapcross-language

mmap a same file in both C and Python, will it really use the shared memory? will mmap work across different programming languages?


By doing the reading from C code and writing from python, I couldn't see in my C the changes that i am doing in python.

Hence I would really like to know whether mmap work across language like C and Python or am I doing mistakes here, Please let me know.

Reading from C Code:

#include <sys/types.h>
#include <sys/mman.h>
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(void)
{
    char *shared;
    int fd = -1;
    if ((fd = open("hello.txt", O_RDWR, 0)) == -1) {
        printf("unable to open");
        return 0;
    }
    shared = (char *)mmap(NULL, 1, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED, -1, 0);
    printf("%c\n",shared[0]);
}

Writing from Python

with open( "hello.txt", "wb" ) as fd:
    fd.write("1")
with open( "hello.txt", "r+b" ) as fd:
    mm = mmap.mmap(fd.fileno(), 1, access=ACCESS_WRITE, offset=0)
    print("content read from file")
    print(mm.readline())
    mm[0] = "0"
    print("content read from file")
    print(mm.readline())
    mm.close()
    fd.close()

Solution

  • In your C program, your mmap() creates an anonymous mapping, not a file-based mapping. You probably want to specify fd instead of -1 and omit the MAP_ANON symbol.

    shared = (char *)mmap(NULL, 1, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);