| 1 |
############################################################################### |
| 2 |
# Launch a subprocess using forkexec and make sure only the needed fd are |
| 3 |
# shared in the two process. |
| 4 |
# |
| 5 |
# author: Thomas Moreau and Olivier Grisel |
| 6 |
# |
| 7 |
import sys |
| 8 |
import os |
| 9 |
import subprocess |
| 10 |
|
| 11 |
|
| 12 |
def fork_exec(cmd, keep_fds, env=None): |
| 13 |
import _posixsubprocess |
| 14 |
|
| 15 |
# Encoded command args as bytes: |
| 16 |
cmd = [os.fsencode(arg) for arg in cmd] |
| 17 |
|
| 18 |
# Copy the environment variables to set in the child process (also encoded |
| 19 |
# as bytes). |
| 20 |
env = env or {} |
| 21 |
env = {**os.environ, **env} |
| 22 |
encoded_env = [] |
| 23 |
for key, value in env.items(): |
| 24 |
encoded_env.append(os.fsencode(f"{key}={value}")) |
| 25 |
|
| 26 |
# Fds with fileno larger than 3 (stdin=0, stdout=1, stderr=2) are be closed |
| 27 |
# in the child process, except for those passed in keep_fds. |
| 28 |
keep_fds = tuple(sorted(map(int, keep_fds))) |
| 29 |
errpipe_read, errpipe_write = os.pipe() |
| 30 |
|
| 31 |
if sys.version_info >= (3, 14): |
| 32 |
# Python >= 3.14 removed allow_vfork from _posixsubprocess.fork_exec, |
| 33 |
# see https://github.com/python/cpython/pull/121383 |
| 34 |
pgid_to_set = [-1] |
| 35 |
allow_vfork = [] |
| 36 |
elif sys.version_info >= (3, 11): |
| 37 |
# Python 3.11 - 3.13 has allow_vfork in _posixsubprocess.fork_exec |
| 38 |
pgid_to_set = [-1] |
| 39 |
allow_vfork = [subprocess._USE_VFORK] |
| 40 |
else: |
| 41 |
# Python < 3.11 |
| 42 |
pgid_to_set = [] |
| 43 |
allow_vfork = [] |
| 44 |
|
| 45 |
try: |
| 46 |
return _posixsubprocess.fork_exec( |
| 47 |
cmd, # args |
| 48 |
cmd[0:1], # executable_list |
| 49 |
True, # close_fds |
| 50 |
keep_fds, # pass_fds |
| 51 |
None, # cwd |
| 52 |
encoded_env, # env |
| 53 |
-1, # p2cread |
| 54 |
-1, # p2cwrite |
| 55 |
-1, # c2pread |
| 56 |
-1, # c2pwrite |
| 57 |
-1, # errread |
| 58 |
-1, # errwrite |
| 59 |
errpipe_read, # errpipe_read |
| 60 |
errpipe_write, # errpipe_write |
| 61 |
False, # restore_signal |
| 62 |
False, # call_setsid |
| 63 |
*pgid_to_set, # pgid_to_set |
| 64 |
None, # gid |
| 65 |
None, # extra_groups |
| 66 |
None, # uid |
| 67 |
-1, # child_umask |
| 68 |
None, # preexec_fn |
| 69 |
*allow_vfork, # extra flag if vfork is available |
| 70 |
) |
| 71 |
finally: |
| 72 |
os.close(errpipe_read) |
| 73 |
os.close(errpipe_write) |