Issue #21619: Popen objects no longer leave a zombie after exit in the with
authorSerhiy Storchaka <storchaka@gmail.com>
Sat, 28 Feb 2015 10:43:08 +0000 (12:43 +0200)
committerSerhiy Storchaka <storchaka@gmail.com>
Sat, 28 Feb 2015 10:43:08 +0000 (12:43 +0200)
statement if the pipe was broken.  Patch by Martin Panter.

Lib/subprocess.py
Lib/test/test_subprocess.py
Misc/NEWS

index bc0ef0b4bea147cdd1ac2d4dfb771dea77031488..f11e538925bc0f8b99c022257fea21a34c49316e 100644 (file)
@@ -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:
index 08af71faade64c9ee189ee654869507e58ee36a2..caa36cfef561bc7a971378a182c9c6c2efbaea68 100644 (file)
@@ -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,
index 8888f79f2f4eb52787c939963908001f413fb6aa..05fde7046d7a924b190f92a2f68be104c58ec9fa 100644 (file)
--- 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.