8

我正在使用多处理模块,并使用池来启动多个工作人员。但是在父进程中打开的文件描述符在工作进程中是关闭的。我希望他们开放..!有没有办法传递文件描述符以在父子之间共享?

4

4 回答 4

9

multiprocessing.reduction在 Python 2 和 Python 3 上,模块中存在用于发送和接收文件描述符的函数。

示例代码(Python 2 和 Python 3):

import multiprocessing
import os

# Before fork
child_pipe, parent_pipe = multiprocessing.Pipe(duplex=True)

child_pid = os.fork()

if child_pid:
    # Inside parent process
    import multiprocessing.reduction
    import socket
    # has socket_to_pass socket object which want to pass to the child
    socket_to_pass = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    socket_to_pass.connect("/dev/log")
    # child_pid argument to send_handle() can be arbitrary on Unix,
    # on Windows it has to be child PID
    multiprocessing.reduction.send_handle(parent_pipe, socket_to_pass.fileno(), child_pid)
    socket_to_pass.send("hello from the parent process\n".encode())
else:
    # Inside child process
    import multiprocessing.reduction
    import socket
    import os
    fd = multiprocessing.reduction.recv_handle(child_pipe)
    # rebuild the socket object from fd
    received_socket = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
    # socket.fromfd() duplicates fd, so we can close the received one
    os.close(fd)
    # and now you can communicate using the received socket
    received_socket.send("hello from the child process\n".encode())
于 2014-12-31T05:06:41.647 回答
3

还有一个multiprocessing被调用的分支multiprocess,它替换pickledilldill可以腌制文件描述符,因此multiprocess可以轻松地在进程之间传递它们。

>>> f = open('test.txt', 'w')
>>> _ = map(f.write, 'hello world')
>>> f.close()
>>> import multiprocess as mp
>>> p = mp.Pool()
>>> f = open('test.txt', 'r')
>>> p.apply(lambda x:x, f)
'hello world'
>>> f.read()
'hello world'
>>> f.close()
于 2016-04-01T21:52:36.417 回答
2

multiprocessing它本身具有用于在 Windows 和 Unix 平台上的进程之间传输文件描述符的辅助方法,支持通过multiprocessing.reduction:send_handlerecv_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 上使用
于 2019-01-04T22:38:59.523 回答
0

我知道没有一种方法可以在进程之间共享文件描述符。如果存在某种方式,它很可能是特定于操作系统的。

我的猜测是您需要在另一个级别上共享数据。

于 2010-06-07T13:20:20.543 回答