2

通过读取 C 代码并从 python 写入,我无法在 C 中看到我在 python 中所做的更改。

因此,我真的很想知道 mmap 是否可以跨 C 和 Python 等语言工作,还是我在这里犯了错误,请告诉我。

从 C 代码读取:

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

从 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()
4

1 回答 1

3

在您的 C 程序中,您mmap()创建了一个匿名映射,而不是基于文件的映射。您可能想要指定fd而不是-1省略MAP_ANON符号。

shared = (char *)mmap(NULL, 1, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
于 2018-02-14T15:46:55.673 回答