|
| 1 | +""" |
| 2 | +Wrappers around multiprocessing.reduction.send_handle/recv_handle |
| 3 | +that |
| 4 | +- fix a bug in CPython’s standard library preventing send_handle from |
| 5 | +working on Windows |
| 6 | +- and translate between Windows handles and Unix file descriptors as necessary. |
| 7 | +""" |
| 8 | + |
| 9 | +import multiprocessing |
| 10 | +import os |
| 11 | + |
| 12 | +try: |
| 13 | + import msvcrt |
| 14 | +except ImportError: |
| 15 | + msvcrt = None |
| 16 | +try: |
| 17 | + import _winapi |
| 18 | +except ImportError: |
| 19 | + _winapi = None |
| 20 | + |
| 21 | + |
| 22 | +class _PatchedDupHandle: |
| 23 | + """Used by _patched_send_handle""" |
| 24 | + |
| 25 | + def __init__(self, handle, access, pid=None, options=0): |
| 26 | + if pid is None: |
| 27 | + pid = os.getpid() |
| 28 | + proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False, pid) |
| 29 | + try: |
| 30 | + self._handle = _winapi.DuplicateHandle( |
| 31 | + _winapi.GetCurrentProcess(), handle, proc, access, False, options |
| 32 | + ) |
| 33 | + finally: |
| 34 | + _winapi.CloseHandle(proc) |
| 35 | + self._access = access |
| 36 | + self._pid = pid |
| 37 | + |
| 38 | + def detach(self): |
| 39 | + if self._pid == os.getpid(): |
| 40 | + return self._handle |
| 41 | + proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False, self._pid) |
| 42 | + try: |
| 43 | + return _winapi.DuplicateHandle( |
| 44 | + proc, |
| 45 | + self._handle, |
| 46 | + _winapi.GetCurrentProcess(), |
| 47 | + self._access, |
| 48 | + False, |
| 49 | + _winapi.DUPLICATE_CLOSE_SOURCE, |
| 50 | + ) |
| 51 | + finally: |
| 52 | + _winapi.CloseHandle(proc) |
| 53 | + |
| 54 | + |
| 55 | +def _patched_send_handle(conn, handle, destination_pid): |
| 56 | + """ |
| 57 | + A patched version of multiprocessing.reduction.send_handle that works around |
| 58 | + bug https://github.com/python/cpython/issues/82369 |
| 59 | + Adapted from code posted by Cameron Kennedy (m3rc1fulcameron) in that issue. |
| 60 | + """ |
| 61 | + dh = _PatchedDupHandle(handle, 0, destination_pid, _winapi.DUPLICATE_SAME_ACCESS) |
| 62 | + conn.send(dh) |
| 63 | + |
| 64 | + |
| 65 | +def send_handle(conn, fd, destination_pid): |
| 66 | + if _winapi is None: |
| 67 | + return multiprocessing.reduction.send_handle(conn, fd, destination_pid) |
| 68 | + else: |
| 69 | + handle = msvcrt.get_osfhandle(fd) |
| 70 | + return _patched_send_handle(conn, handle, destination_pid) |
| 71 | + |
| 72 | + |
| 73 | +def recv_handle(conn): |
| 74 | + handle = multiprocessing.reduction.recv_handle(conn) |
| 75 | + if msvcrt: |
| 76 | + return msvcrt.open_osfhandle(handle, os.O_RDONLY | os.O_BINARY) |
| 77 | + else: |
| 78 | + return handle |
0 commit comments