2 回答
TA贡献1883条经验 获得超3个赞
这是一些开箱即用的示例代码!:test_mmap.py
import os, ctypes, posix_ipc, sys, mmap
from subprocess import call
SHARED_MEMORY_NAME = "/shared_memory"
memory = posix_ipc.SharedMemory(SHARED_MEMORY_NAME, posix_ipc.O_CREX,
size=1024)
mapFile = mmap.mmap(memory.fd, memory.size)
memory.close_fd()
mapFile.seek(0)
mapFile.write("Hello world!\n".encode('utf-8'))
mapFile.seek(0)
print("FROM PYTHON MAIN PROCESS: ", mapFile.readline().decode('utf-8'))
mapFile.seek(0)
call([
"node", "./test_mmap.js", SHARED_MEMORY_NAME
])
mapFile.close()
posix_ipc.unlink_shared_memory(SHARED_MEMORY_NAME)
test_mmap.js
const args = process.argv;
const mmap = require('mmap.js');
const shm = require('nodeshm');
const SHM_FILE_NAME=args[args.length-1];
let fd = shm.shm_open(SHM_FILE_NAME, shm.O_RDWR, 0600);
if (fd == -1){
console.log("FD COULD NOT BE OPENED!");
throw "here";
}
let mm = mmap.alloc(1024, mmap.PROT_READ | mmap.PROT_WRITE, mmap.MAP_SHARED, fd, 0);
console.log("FROM NODE: ", mm.slice(0, mm.indexOf('\n')).toString('utf-8'));
示例输出:
FROM PYTHON MAIN PROCESS: Hello world!
FROM NODE: Hello world!
TA贡献1946条经验 获得超3个赞
幸运的是,这不起作用:想象一下,如果所有系统的MAP_ANONYMOUS
映射都针对同一区域并不断相互覆盖,那将是多么混乱。
相反,使用shm_open
创建一个新句柄,您可以在两个进程中进行 mmap。这是一个可移植的包装器,围绕同样有效但可移植性较差的策略创建和映射/dev/shm/
.
添加回答
举报