Skip to content

Commit da77cb6

Browse files
duanegefimov-mikhailvstinner
authored andcommitted
pythongh-135335: flush stdout/stderr in forkserver after preloading modules (python#135338)
If a preloaded module writes to stdout or stderr, and the stream is buffered, child processes will inherit the buffered data after forking. Attempt to prevent this by flushing the streams after preload. Co-authored-by: Mikhail Efimov <[email protected]> Co-authored-by: Victor Stinner <[email protected]>
1 parent 9f18cdf commit da77cb6

File tree

4 files changed

+50
-0
lines changed

4 files changed

+50
-0
lines changed

Lib/multiprocessing/forkserver.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,10 @@ def main(listener_fd, alive_r, preload, main_path=None, sys_path=None,
222222
except ImportError:
223223
pass
224224

225+
# gh-135335: flush stdout/stderr in case any of the preloaded modules
226+
# wrote to them, otherwise children might inherit buffered data
227+
util._flush_std_streams()
228+
225229
util._close_stdin()
226230

227231
sig_r, sig_w = os.pipe()

Lib/test/_test_multiprocessing.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6801,6 +6801,35 @@ def test_child_sys_path(self):
68016801
self.assertEqual(child_sys_path[1:], sys.path[1:])
68026802
self.assertIsNone(import_error, msg=f"child could not import {self._mod_name}")
68036803

6804+
def test_std_streams_flushed_after_preload(self):
6805+
# gh-135335: Check fork server flushes standard streams after
6806+
# preloading modules
6807+
if multiprocessing.get_start_method() != "forkserver":
6808+
self.skipTest("forkserver specific test")
6809+
6810+
# Create a test module in the temporary directory on the child's path
6811+
# TODO: This can all be simplified once gh-126631 is fixed and we can
6812+
# use __main__ instead of a module.
6813+
dirname = os.path.join(self._temp_dir, 'preloaded_module')
6814+
init_name = os.path.join(dirname, '__init__.py')
6815+
os.mkdir(dirname)
6816+
with open(init_name, "w") as f:
6817+
cmd = '''if 1:
6818+
import sys
6819+
print('stderr', end='', file=sys.stderr)
6820+
print('stdout', end='', file=sys.stdout)
6821+
'''
6822+
f.write(cmd)
6823+
6824+
name = os.path.join(os.path.dirname(__file__), 'mp_preload_flush.py')
6825+
env = {'PYTHONPATH': self._temp_dir}
6826+
_, out, err = test.support.script_helper.assert_python_ok(name, **env)
6827+
6828+
# Check stderr first, as it is more likely to be useful to see in the
6829+
# event of a failure.
6830+
self.assertEqual(err.decode().rstrip(), 'stderr')
6831+
self.assertEqual(out.decode().rstrip(), 'stdout')
6832+
68046833

68056834
class MiscTestCase(unittest.TestCase):
68066835
def test__all__(self):

Lib/test/mp_preload_flush.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import multiprocessing
2+
import sys
3+
4+
modname = 'preloaded_module'
5+
if __name__ == '__main__':
6+
if modname in sys.modules:
7+
raise AssertionError(f'{modname!r} is not in sys.modules')
8+
multiprocessing.set_start_method('forkserver')
9+
multiprocessing.set_forkserver_preload([modname])
10+
for _ in range(2):
11+
p = multiprocessing.Process()
12+
p.start()
13+
p.join()
14+
elif modname not in sys.modules:
15+
raise AssertionError(f'{modname!r} is not in sys.modules')
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:mod:`multiprocessing`: Flush ``stdout`` and ``stderr`` after preloading
2+
modules in the ``forkserver``.

0 commit comments

Comments
 (0)