Skip to content

Commit 5654f83

Browse files
alpiremiss-islington
authored andcommitted
[3.8] bpo-35182: fix communicate() crash after child closes its pipes (GH-18117) (GH-18148)
When communicate() is called in a loop, it crashes when the child process has already closed any piped standard stream, but still continues to be running Co-authored-by: Andriy Maletsky <[email protected]>. (cherry picked from commit d3ae95e) Co-authored-by: Alex Rebert <[email protected]> https://bugs.python.org/issue35182
1 parent 5a2356b commit 5654f83

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

Lib/subprocess.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1848,9 +1848,9 @@ def _communicate(self, input, endtime, orig_timeout):
18481848
with _PopenSelector() as selector:
18491849
if self.stdin and input:
18501850
selector.register(self.stdin, selectors.EVENT_WRITE)
1851-
if self.stdout:
1851+
if self.stdout and not self.stdout.closed:
18521852
selector.register(self.stdout, selectors.EVENT_READ)
1853-
if self.stderr:
1853+
if self.stderr and not self.stderr.closed:
18541854
selector.register(self.stderr, selectors.EVENT_READ)
18551855

18561856
while selector.get_map():

Lib/test/test_subprocess.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2910,6 +2910,17 @@ def test_stopped(self):
29102910

29112911
self.assertEqual(returncode, -3)
29122912

2913+
def test_communicate_repeated_call_after_stdout_close(self):
2914+
proc = subprocess.Popen([sys.executable, '-c',
2915+
'import os, time; os.close(1), time.sleep(2)'],
2916+
stdout=subprocess.PIPE)
2917+
while True:
2918+
try:
2919+
proc.communicate(timeout=0.1)
2920+
return
2921+
except subprocess.TimeoutExpired:
2922+
pass
2923+
29132924

29142925
@unittest.skipUnless(mswindows, "Windows specific tests")
29152926
class Win32ProcessTestCase(BaseTestCase):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fixed :func:`Popen.communicate` subsequent call crash when the child process
2+
has already closed any piped standard stream, but still continues to be
3+
running. Patch by Andriy Maletsky.

0 commit comments

Comments
 (0)