Fixed bug #1531862: Do not close standard file descriptors in subprocess.

Let's try that once more. Buildbots were broken last time, but probably
because tests were sending data to stderr for testing it (sending to a
file doesn't touch the problem).

The fix is still the same, but tests were reduced (removing tests to
be able to fix something is weird, but oh well).
diff --git a/Lib/subprocess.py b/Lib/subprocess.py
index 5438f15..7c229dc 100644
--- a/Lib/subprocess.py
+++ b/Lib/subprocess.py
@@ -1000,14 +1000,10 @@
                     if errwrite:
                         os.dup2(errwrite, 2)
 
-                    # Close pipe fds.  Make sure we doesn't close the same
-                    # fd more than once.
-                    if p2cread:
-                        os.close(p2cread)
-                    if c2pwrite and c2pwrite not in (p2cread,):
-                        os.close(c2pwrite)
-                    if errwrite and errwrite not in (p2cread, c2pwrite):
-                        os.close(errwrite)
+                    # Close pipe fds.  Make sure we don't close the same
+                    # fd more than once, or standard fds.
+                    for fd in set((p2cread, c2pwrite, errwrite))-set((0,1,2)):
+                        if fd: os.close(fd)
 
                     # Close all other fds, if asked for
                     if close_fds:
diff --git a/Lib/test/test_subprocess.py b/Lib/test/test_subprocess.py
index 8c8ac40..19a31ea 100644
--- a/Lib/test/test_subprocess.py
+++ b/Lib/test/test_subprocess.py
@@ -234,6 +234,18 @@
         stripped = remove_stderr_debug_decorations(output)
         self.assertEqual(stripped, "appleorange")
 
+    def test_stdout_filedes_of_stdout(self):
+        # stdout is set to 1 (#1531862).
+        cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), '.\n'))"
+        rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
+        self.assertEquals(rc, 2)
+
+    def test_stdout_fileobj_of_stdout(self):
+        # stdout is set to sys.stdout (#1531862).
+        cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), '.\n'))"
+        rc = subprocess.call([sys.executable, "-c", cmd], stdout=sys.stdout)
+        self.assertEquals(rc, 2)
+
     def test_cwd(self):
         tmpdir = os.getenv("TEMP", "/tmp")
         # We cannot use os.path.realpath to canonicalize the path,
diff --git a/Misc/NEWS b/Misc/NEWS
index 2cad993..53708c1 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -56,6 +56,8 @@
 
 - Bug #1543303, patch #1543897: remove NUL padding from tarfiles.
 
+- Bug #1531862: Do not close standard file descriptors in subprocess.
+
 
 Extension Modules
 -----------------