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

Mapping the same file in C and Python, will it really use shared memory? Does mmap work across different programming languages?… here is a solution to the problem.

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

By reading from C code and writing from python, I can’t see the changes I made in python in my C.

So I’m really wondering if mmap works across languages like C and Python or I’m doing something wrong here, please let me know.

Read 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]);
}

Written in 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 instead of a file-based mapping. You may 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);

Related Problems and Solutions