@@ -4450,6 +4450,40 @@ def test_fast_path_avoid_busy_loop(self):
44504450 self .assertEqual (p .wait (timeout = support .LONG_TIMEOUT ), 0 )
44514451 self .assertFalse (m .called )
44524452
4453+ @unittest .skipIf (mswindows , "requires the POSIX wait implementation" )
4454+ def test_wait_timeout_not_shortened_in_reap_race (self ):
4455+ # gh-162438: when the fast wait reports an exit but the first
4456+ # waitpid(WNOHANG) cannot reap the child yet, _wait() falls back
4457+ # to busy polling. It used to subtract the elapsed time from an
4458+ # already-absolute deadline, which made wait(timeout=T) expire
4459+ # as soon as more than half of T had elapsed before the fallback,
4460+ # losing the child's exit status.
4461+ p = subprocess .Popen (ZERO_RETURN_CMD )
4462+ real_try_wait = p ._try_wait
4463+ ncalls = 0
4464+
4465+ def racy_try_wait (flags ):
4466+ nonlocal ncalls
4467+ ncalls += 1
4468+ if ncalls <= 2 :
4469+ # poll()/kqueue() reported the exit, but the child is
4470+ # still not reapable on the first two attempts.
4471+ return (0 , 0 )
4472+ return real_try_wait (flags )
4473+
4474+ def exit_reported_late (self , timeout ):
4475+ # Simulate the fast wait noticing the exit after most of
4476+ # the caller's timeout has already elapsed.
4477+ time .sleep (0.25 )
4478+ return True
4479+
4480+ with mock .patch .object (subprocess .Popen , "_wait_pidfd" ,
4481+ exit_reported_late ), \
4482+ mock .patch .object (subprocess .Popen , "_wait_kqueue" ,
4483+ exit_reported_late ), \
4484+ mock .patch .object (p , "_try_wait" , racy_try_wait ):
4485+ self .assertEqual (p .wait (timeout = 0.4 ), 0 )
4486+
44534487 @unittest .skipIf (mswindows , "requires the POSIX wait implementation" )
44544488 def test_wait_huge_timeout (self ):
44554489 # gh-154836: very large timeout values used to overflow the C
0 commit comments