【问题标题】:mmap a same file in both C and Python, will it really use the shared memory? will mmap work across different programming languages?在 C 和 Python 中映射同一个文件,它真的会使用共享内存吗? mmap 可以跨不同的编程语言工作吗?
【发布时间】:2018-02-14 15:26:43
【问题描述】:

通过读取 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()

【问题讨论】:

  • 您的 C 代码创建了一个匿名映射。您的 Python 代码映射了一个名为“hello.txt”的文件。他们最好不要是同一个映射。还是您打算在您的 C 程序中映射“hello.txt”?
  • 是的,我打算将 hello.txt 映射到我的 c 程序中。我只尝试了 MAP_SHARED 但无法使其工作。我认为,使用相同的文件执行 mmap 将开始从文件的映射内存区域提供数据,而不是完全从文件中提供数据。

标签: python c mmap cross-language


【解决方案1】:

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

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

【讨论】:

  • 非常感谢罗伯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
  • 1970-01-01
相关资源
最近更新 更多