Repository navigation
Fix Subprocess.wait_for_exit hanging when child is already reaped - #3791
inchang-ing wants to merge 1 commit into
Conversation
If the child process has already been reaped (for example by a direct call to subprocess.Popen.wait) before wait_for_exit / set_exit_callback is invoked, os.waitpid raises ChildProcessError. The previous code swallowed this exception and returned without resolving the Future, so wait_for_exit would hang forever (tornado#3364). Now resolve the exit status from the Popen object (proc.returncode, which is already in decoded form) when the pid is still being waited on. fixes tornadoweb#3364
| # ``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: |
There was a problem hiding this comment.
If subproc.proc.returncode is None, this will still wait forever. This fixes things for the specific case of using both proc.wait() and await proc.wait_for_exit(), but that's not the only way processes can be reaped (and it doesn't seem likely to me that someone would use these two methods together).
I'm more concerned about action at a distance via the os.wait() function. This waits for an unspecified child process and reaps the first one it finds. Basically it never makes sense to use os.wait() and os.waitpid() in the same process, since wait makes waitpid unpredictable. But we can't control what else happens in the process so I think there's a good chance this is what happened in #3364.
I'm not sure there's anything we can do to handle that situation cleanly (the exit status of the child process is lost to us if we don't control the call to os.wait()). If we deprecated set_exit_callback we could cause wait_for_exit to raise an error. Or we could just log an error and hope that's enough to get someone to dig into their use of os.wait().
Summary
Fixes #3364.
Subprocess.wait_for_exit(andset_exit_callback) eventually callos.waitpid. If the child process has already been reaped — for example by a direct call tosubprocess.Popen.wait()beforewait_for_exitis invoked —os.waitpidraisesChildProcessError. The previous code swallowed this exception and returned without resolving the Future, sowait_for_exithung forever.Now, when
ChildProcessErroris raised and the pid is still being waited on, the Subprocess is retrieved from the_waitingdict and its exit status is resolved from thePopenobject (proc.returncode, which is already in the decoded form tornado uses) instead of going throughos.waitpidagain.Reproduction
Test plan
test_wait_for_exit_after_proc_waitandtest_wait_for_exit_after_proc_wait_nonzerototornado/test/process_test.py(Unix-only, matching the bug's availability).