gpt4 book ai didi

python - 如何在python中将文件描述符从父级传递给子级?

转载 作者:太空狗 更新时间:2023-10-29 22:17:13 26 4
gpt4 key购买 nike

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

最佳答案

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

示例代码(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())

关于python - 如何在python中将文件描述符从父级传递给子级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2989823/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com