diff --git a/tornado/process.py b/tornado/process.py index 493481fd18..ac5b0eb3b2 100644 --- a/tornado/process.py +++ b/tornado/process.py @@ -336,6 +336,14 @@ def _try_cleanup_process(cls, pid: int) -> None: try: ret_pid, status = os.waitpid(pid, os.WNOHANG) # type: ignore except ChildProcessError: + # The child has already been reaped by something else (for + # example a direct call to ``subprocess.Popen.wait``). If we + # were waiting on it, resolve its exit status from the + # ``Popen`` object so that ``wait_for_exit`` / + # ``set_exit_callback`` don't hang forever. + subproc = cls._waiting.pop(pid, None) + if subproc is not None and subproc.proc.returncode is not None: + subproc.io_loop.add_callback(subproc._set_returncode_from_popen) return if ret_pid == 0: return @@ -360,3 +368,15 @@ def _set_returncode(self, status: int) -> None: callback = self._exit_callback self._exit_callback = None callback(self.returncode) + + def _set_returncode_from_popen(self) -> None: + # The process was reaped elsewhere (e.g. ``subprocess.Popen.wait``), + # so ``proc.returncode`` is already in the decoded form that + # ``_set_returncode`` would produce. Reuse it directly instead of + # going through ``os.waitpid`` again, which would raise + # ``ChildProcessError``. + self.returncode = self.proc.returncode + if self._exit_callback: + callback = self._exit_callback + self._exit_callback = None + callback(self.returncode) diff --git a/tornado/test/process_test.py b/tornado/test/process_test.py index 9c2855165a..0f2a8562c2 100644 --- a/tornado/test/process_test.py +++ b/tornado/test/process_test.py @@ -292,3 +292,29 @@ def test_wait_for_exit_raise_disabled(self): subproc = Subprocess([sys.executable, "-c", "import sys; sys.exit(1)"]) ret = yield subproc.wait_for_exit(raise_error=False) self.assertEqual(ret, 1) + + @gen_test + def test_wait_for_exit_after_proc_wait(self): + # Regression test for https://github.com/tornadoweb/tornado/issues/3364 + # If the child has already been reaped (e.g. via a direct call to + # ``subprocess.Popen.wait``) before ``wait_for_exit`` is called, the + # returned Future must still resolve instead of hanging forever. + Subprocess.initialize() + self.addCleanup(Subprocess.uninitialize) + subproc = Subprocess([sys.executable, "-c", "pass"]) + subproc.proc.wait() + ret = yield subproc.wait_for_exit() + self.assertEqual(ret, 0) + self.assertEqual(subproc.returncode, ret) + + @gen_test + def test_wait_for_exit_after_proc_wait_nonzero(self): + # Same as above but with a non-zero exit status to verify the + # decoded return code is propagated correctly. + Subprocess.initialize() + self.addCleanup(Subprocess.uninitialize) + subproc = Subprocess([sys.executable, "-c", "import sys; sys.exit(3)"]) + subproc.proc.wait() + ret = yield subproc.wait_for_exit(raise_error=False) + self.assertEqual(ret, 3) + self.assertEqual(subproc.returncode, ret)