From ab900c21fcfb08f13467d1c6f47d03ab90180f89 Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Sat, 28 Feb 2015 12:43:08 +0200 Subject: [PATCH] Issue #21619: Popen objects no longer leave a zombie after exit in the with statement if the pipe was broken. Patch by Martin Panter. --- Lib/subprocess.py | 10 ++++++---- Lib/test/test_subprocess.py | 15 +++++++++++++++ Misc/NEWS | 3 +++ 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/Lib/subprocess.py b/Lib/subprocess.py index bc0ef0b4bea..f11e538925b 100644 --- a/Lib/subprocess.py +++ b/Lib/subprocess.py @@ -896,10 +896,12 @@ class Popen(object): self.stdout.close() if self.stderr: self.stderr.close() - if self.stdin: - self.stdin.close() - # Wait for the process to terminate, to avoid zombies. - self.wait() + try: # Flushing a BufferedWriter may raise an error + if self.stdin: + self.stdin.close() + finally: + # Wait for the process to terminate, to avoid zombies. + self.wait() def __del__(self, _maxsize=sys.maxsize): if not self._child_created: diff --git a/Lib/test/test_subprocess.py b/Lib/test/test_subprocess.py index 08af71faade..caa36cfef56 100644 --- a/Lib/test/test_subprocess.py +++ b/Lib/test/test_subprocess.py @@ -2521,6 +2521,21 @@ class ContextManagerTests(BaseTestCase): stderr=subprocess.PIPE) as proc: pass + def test_broken_pipe_cleanup(self): + """Broken pipe error should not prevent wait() (Issue 21619)""" + proc = subprocess.Popen([sys.executable, "-c", + "import sys;" + "sys.stdin.close();" + "sys.stdout.close();" # Signals that input pipe is closed + ], stdin=subprocess.PIPE, stdout=subprocess.PIPE) + proc.stdout.read() # Make sure subprocess has closed its input + proc.stdin.write(b"buffered data") + self.assertIsNone(proc.returncode) + self.assertRaises(BrokenPipeError, proc.__exit__, None, None, None) + self.assertEqual(0, proc.returncode) + self.assertTrue(proc.stdin.closed) + self.assertTrue(proc.stdout.closed) + def test_main(): unit_tests = (ProcessTestCase, diff --git a/Misc/NEWS b/Misc/NEWS index 8888f79f2f4..05fde7046d7 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -13,6 +13,9 @@ Core and Builtins Library ------- +- Issue #21619: Popen objects no longer leave a zombie after exit in the with + statement if the pipe was broken. Patch by Martin Panter. + - Issue #6639: Module-level turtle functions no longer raise TclError after closing the window.