启动一个新进程并为其共享一个对象(共享内存)
进程 #1 是否可以使用 Popen
启动进程 #2,并向其传递对字典 D
的引用,以便进程 #2 可以读取其内容?
# process1.py
import subprocess, time
D = {'foo': 'bar'}
subprocess.Popen(['python3', 'process2.py', str(id(D))])
time.sleep(3600)
# process2.py
import sys
ref = sys.argv[1] # can we turn this address into an (at least read-only) object?
# and read foo/bar?
如果没有,我知道 socket
(以及涉及网络的更一般的消息传递技术)、Linux 上的 /dev/shm
以及这些 IPC 技术 使两个不同的进程进行通信,但是是否有更简单的解决方案,仅共享内存中的对象< /强>?
我想,出于安全原因,进程应该使用特殊选项来启动,以授权其内存与其他进程共享。
Can a process #1 start a process #2 with Popen
, and pass to it a reference to a dict D
, so that process #2 can read its content?
# process1.py
import subprocess, time
D = {'foo': 'bar'}
subprocess.Popen(['python3', 'process2.py', str(id(D))])
time.sleep(3600)
# process2.py
import sys
ref = sys.argv[1] # can we turn this address into an (at least read-only) object?
# and read foo/bar?
If not, I know sockets
(and more generally messaging techniques involving networking), /dev/shm
on Linux, and these IPC techniques to make 2 different processes communicate, but are there even simpler solutions by just sharing an in-memory object?
I guess, for security reasons, the processes should be started with a special option to authorize its memory to be shared with other processes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
经过进一步研究,似乎
mmap
非常适合这种情况(但请注意,它不会共享对象,而只是共享字节。不过,pickle 可用于序列化)。因此,这是一个非常简单的共享内存进程间通信,无需使用套接字:
服务器:
客户端:
注意:这仅适用于 Windows:
视频数据的另一个示例: https://github.com/off99555/python-mmap-ipc< /a>
After further research, it seems
mmap
is perfect for this (but note that it will not share an object but justbytes
.pickle
can be used for the serialization though).Thus, this is a very simple shared-memory inter process communication without using a socket:
Server:
Client:
Note: this is only for Windows:
Another example with video data: https://github.com/off99555/python-mmap-ipc