如何在python中将文件描述符从父级传递给子级?
我正在使用多处理模块,并使用池来启动多个工作人员。但是在父进程中打开的文件描述符在工作进程中被关闭。我希望他们开放..!有没有办法传递文件描述符以在父级和子级之间共享?
I am using multiprocessing module, and using pools to start multiple workers. But the file descriptors which are opened at the parent process are closed in the worker processes. I want them to be open..! Is there any way to pass file descriptors to be shared across parent and children?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Python 2 和 Python 3 上,
multiprocessing.reduction
模块中存在用于发送和接收文件描述符的函数。示例代码(Python 2 和 Python 3):
On Python 2 and Python 3, functions for sending and receiving file descriptors exist in
multiprocessing.reduction
module.Example code (Python 2 and Python 3):
还有一个名为
multiprocess
的multiprocessing
分支,它用dill
取代了pickle
。dill
可以 pickle 文件描述符,因此multiprocess
可以轻松地在进程之间传递它们。There is also a fork of
multiprocessing
calledmultiprocess
, which replacespickle
withdill
.dill
can pickle file descriptors, and thusmultiprocess
can easily pass them between processes.multiprocessing
本身具有用于在 Windows 和 Unix 平台上的进程之间传输文件描述符的辅助方法,这些方法支持在multiprocessing.reduction
中通过 Unix 域套接字发送文件描述符:send_handle
代码>和<代码>recv_handle。这些没有记录,但在模块的__all__
中,因此可以安全地假设它们是公共 API 的一部分。从消息来源来看,这些功能至少从 2.6+ 和 3.3+ 版本就已经可用。所有平台都具有相同的接口:
send_handle(conn,handle,destination_pid)
recv_handle(conn)
其中:
conn
(multiprocessing.Connection
):连接发送文件描述符handle
(int
):引用文件描述符/句柄的整数destination_pid
(int
):接收文件描述符的进程的整数 pid - 目前仅在 Windows 上使用multiprocessing
itself has helper methods for transferring file descriptors between processes on Windows and Unix platforms that support sending file descriptors over Unix domain sockets inmultiprocessing.reduction
:send_handle
andrecv_handle
. These are not documented but are in the module's__all__
so it may be safe to assume they are part of the public API. From the source it looks like these have been available since at least 2.6+ and 3.3+.All platforms have the same interface:
send_handle(conn, handle, destination_pid)
recv_handle(conn)
Where:
conn
(multiprocessing.Connection
): connection over which to send the file descriptorhandle
(int
): integer referring to file descriptor/handledestination_pid
(int
): integer pid of the process that is receiving the file descriptor - this is currently only used on Windows据我所知,没有一种方法可以在进程之间共享文件描述符。
如果存在某种方法,它很可能是特定于操作系统的。
我的猜测是您需要在另一个层面上共享数据。
There isn't a way that I know of to share file descriptors between processes.
If a way exists, it is most likely OS specific.
My guess is that you need to share data on another level.