[Python-checkins] cpython (merge 3.4 -> default): Issue #21619: Popen objects no longer leave a zombie after exit in the with

serhiy.storchaka python-checkins at python.org
Sat Feb 28 11:46:45 CET 2015


https://hg.python.org/cpython/rev/cdac249808a8
changeset:   94783:cdac249808a8
parent:      94781:de6d278c432a
parent:      94782:b5e9ddbdd4a7
user:        Serhiy Storchaka <storchaka at gmail.com>
date:        Sat Feb 28 12:45:00 2015 +0200
summary:
  Issue #21619: Popen objects no longer leave a zombie after exit in the with
statement if the pipe was broken.  Patch by Martin Panter.

files:
  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
--- a/Lib/subprocess.py
+++ b/Lib/subprocess.py
@@ -892,10 +892,12 @@
             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
--- a/Lib/test/test_subprocess.py
+++ b/Lib/test/test_subprocess.py
@@ -2502,6 +2502,21 @@
                                   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
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -13,6 +13,9 @@
 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 #15955: Add an option to limit the output size in bz2.decompress().
   Patch by Nikolaus Rath.
 

-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list