]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Issue #3210: Ensure stdio handles are closed if CreateProcess fails
authorTim Golden <mail@timgolden.me.uk>
Fri, 6 Aug 2010 13:20:12 +0000 (13:20 +0000)
committerTim Golden <mail@timgolden.me.uk>
Fri, 6 Aug 2010 13:20:12 +0000 (13:20 +0000)
Lib/test/test_subprocess.py
PC/_subprocess.c

index 5cdbe2dd7e6590aa8adc86ded9d4a5ac14938302..ff9945b70eb779fbe3dde8c744824c64570ce711 100644 (file)
@@ -548,6 +548,26 @@ class ProcessTestCase(unittest.TestCase):
         output = subprocess.check_output([sys.executable, '-c', code])
         self.assert_(output.startswith(b'Hello World!'), ascii(output))
 
+    def test_handles_closed_on_exception(self):
+        # If CreateProcess exits with an error, ensure the
+        # duplicate output handles are released
+        ifhandle, ifname = self.mkstemp()
+        ofhandle, ofname = self.mkstemp()
+        efhandle, efname = self.mkstemp()
+        try:
+            subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
+              stderr=efhandle)
+        except OSError:
+            os.close(ifhandle)
+            os.remove(ifname)
+            os.close(ofhandle)
+            os.remove(ofname)
+            os.close(efhandle)
+            os.remove(efname)
+        self.assertFalse(os.path.exists(ifname))
+        self.assertFalse(os.path.exists(ofname))
+        self.assertFalse(os.path.exists(efname))
+
     #
     # POSIX tests
     #
index 27d3dc69c85f8bd3ceb300c4d3020708a15d2ab7..635abc8088e3cc128f7450aa8a66baaa5a27124c 100644 (file)
@@ -429,6 +429,7 @@ sp_CreateProcess(PyObject* self, PyObject* args)
     PyObject* env_mapping;
     Py_UNICODE* current_directory;
     PyObject* startup_info;
+    DWORD error;
 
     if (! PyArg_ParseTuple(args, "ZZOOiiOZO:CreateProcess",
                            &application_name,
@@ -478,8 +479,22 @@ sp_CreateProcess(PyObject* self, PyObject* args)
 
     Py_XDECREF(environment);
 
-    if (! result)
-        return PyErr_SetFromWindowsErr(GetLastError());
+    if (! result) {
+        error = GetLastError();
+        if(si.hStdInput != INVALID_HANDLE_VALUE) {
+            CloseHandle(si.hStdInput);
+            si.hStdInput = INVALID_HANDLE_VALUE;
+        }
+        if(si.hStdOutput != INVALID_HANDLE_VALUE) {
+            CloseHandle(si.hStdOutput);
+            si.hStdOutput = INVALID_HANDLE_VALUE;
+        }
+        if(si.hStdError != INVALID_HANDLE_VALUE) {
+            CloseHandle(si.hStdError);
+            si.hStdError = INVALID_HANDLE_VALUE;
+        }
+        return PyErr_SetFromWindowsErr(error);
+    }
 
     return Py_BuildValue("NNii",
                          sp_handle_new(pi.hProcess),