@@ -6007,8 +6007,9 @@ def test_resource_tracker_sigkill(self):
60076007 def _is_resource_tracker_reused (conn , pid ):
60086008 from multiprocessing .resource_tracker import _resource_tracker
60096009 _resource_tracker .ensure_running ()
6010- # The pid should be None in the child process, expect for the fork
6011- # context. It should not be a new value.
6010+ # The pid should be None in the child (the at-fork handler clears
6011+ # it for fork; spawn/forkserver children never had it set). It
6012+ # should not be a new value.
60126013 reused = _resource_tracker ._pid in (None , pid )
60136014 reused &= _resource_tracker ._check_alive ()
60146015 conn .send (reused )
@@ -6093,6 +6094,183 @@ def test_resource_tracker_blocked_signals(self):
60936094 # restore sigmask to what it was before executing test
60946095 signal .pthread_sigmask (signal .SIG_SETMASK , orig_sigmask )
60956096
6097+ @only_run_in_forkserver_testsuite ("avoids redundant testing." )
6098+ def test_resource_tracker_fork_deadlock (self ):
6099+ # gh-146313: ResourceTracker.__del__ used to deadlock if a forked
6100+ # child still held the pipe's write end open when the parent
6101+ # exited, because the parent would block in waitpid() waiting for
6102+ # the tracker to exit, but the tracker would never see EOF.
6103+ cmd = '''if 1:
6104+ import os, signal
6105+ from multiprocessing.resource_tracker import ensure_running
6106+ ensure_running()
6107+ if os.fork() == 0:
6108+ signal.pause()
6109+ os._exit(0)
6110+ # parent falls through and exits, triggering __del__
6111+ '''
6112+ proc = subprocess .Popen ([sys .executable , '-c' , cmd ],
6113+ start_new_session = True )
6114+ try :
6115+ try :
6116+ proc .wait (timeout = support .SHORT_TIMEOUT )
6117+ except subprocess .TimeoutExpired :
6118+ self .fail (
6119+ "Parent process deadlocked in ResourceTracker.__del__"
6120+ )
6121+ self .assertEqual (proc .returncode , 0 )
6122+ finally :
6123+ try :
6124+ os .killpg (proc .pid , signal .SIGKILL )
6125+ except ProcessLookupError :
6126+ pass
6127+ proc .wait ()
6128+
6129+ @only_run_in_forkserver_testsuite ("avoids redundant testing." )
6130+ def test_resource_tracker_mp_fork_reuse_and_prompt_reap (self ):
6131+ # gh-146313 / gh-80849: A child started via multiprocessing.Process
6132+ # with the 'fork' start method should reuse the parent's resource
6133+ # tracker (the at-fork handler preserves the inherited pipe fd),
6134+ # *and* the parent should be able to reap the tracker promptly
6135+ # after joining the child, without hitting the waitpid timeout.
6136+ cmd = textwrap .dedent ('''
6137+ import multiprocessing as mp
6138+ from multiprocessing.resource_tracker import _resource_tracker
6139+
6140+ def child(conn):
6141+ # Prove we can talk to the parent's tracker by registering
6142+ # and unregistering a dummy resource over the inherited fd.
6143+ # If the fd were closed, ensure_running would launch a new
6144+ # tracker and _pid would be non-None.
6145+ _resource_tracker.register("x", "dummy")
6146+ _resource_tracker.unregister("x", "dummy")
6147+ conn.send((_resource_tracker._fd is not None,
6148+ _resource_tracker._pid is None,
6149+ _resource_tracker._check_alive()))
6150+
6151+ if __name__ == "__main__":
6152+ mp.set_start_method("fork")
6153+ _resource_tracker.ensure_running()
6154+ r, w = mp.Pipe(duplex=False)
6155+ p = mp.Process(target=child, args=(w,))
6156+ p.start()
6157+ child_has_fd, child_pid_none, child_alive = r.recv()
6158+ p.join()
6159+ w.close(); r.close()
6160+
6161+ # Now simulate __del__: the child has exited and released
6162+ # its fd copy, so the tracker should see EOF and exit
6163+ # promptly -- no timeout.
6164+ _resource_tracker._stop(wait_timeout=5.0)
6165+ print(child_has_fd, child_pid_none, child_alive,
6166+ _resource_tracker._waitpid_timed_out,
6167+ _resource_tracker._exitcode)
6168+ ''' )
6169+ rc , out , err = script_helper .assert_python_ok ('-c' , cmd )
6170+ parts = out .decode ().split ()
6171+ self .assertEqual (parts , ['True' , 'True' , 'True' , 'False' , '0' ],
6172+ f"unexpected: { parts !r} stderr={ err !r} " )
6173+
6174+ @only_run_in_forkserver_testsuite ("avoids redundant testing." )
6175+ def test_resource_tracker_raw_fork_prompt_reap (self ):
6176+ # gh-146313: After a raw os.fork() the at-fork handler closes the
6177+ # child's inherited fd, so the parent can reap the tracker
6178+ # immediately -- even while the child is still alive -- rather
6179+ # than waiting out the 1s timeout.
6180+ cmd = textwrap .dedent ('''
6181+ import os, signal
6182+ from multiprocessing.resource_tracker import _resource_tracker
6183+
6184+ _resource_tracker.ensure_running()
6185+ r, w = os.pipe()
6186+ pid = os.fork()
6187+ if pid == 0:
6188+ os.close(r)
6189+ # Report whether our fd was closed by the at-fork handler.
6190+ os.write(w, b"1" if _resource_tracker._fd is None else b"0")
6191+ os.close(w)
6192+ signal.pause() # stay alive so parent's reap is meaningful
6193+ os._exit(0)
6194+ os.close(w)
6195+ child_fd_closed = os.read(r, 1) == b"1"
6196+ os.close(r)
6197+
6198+ # Child is still alive and paused. Because it closed its fd
6199+ # copy, our close below is the last one and the tracker exits.
6200+ _resource_tracker._stop(wait_timeout=5.0)
6201+
6202+ os.kill(pid, signal.SIGKILL)
6203+ os.waitpid(pid, 0)
6204+ print(child_fd_closed,
6205+ _resource_tracker._waitpid_timed_out,
6206+ _resource_tracker._exitcode)
6207+ ''' )
6208+ rc , out , err = script_helper .assert_python_ok ('-c' , cmd )
6209+ parts = out .decode ().split ()
6210+ self .assertEqual (parts , ['True' , 'False' , '0' ],
6211+ f"unexpected: { parts !r} stderr={ err !r} " )
6212+
6213+ @only_run_in_forkserver_testsuite ("avoids redundant testing." )
6214+ def test_resource_tracker_lock_reinit_after_fork (self ):
6215+ # gh-146313: If a parent thread held the tracker's lock at fork
6216+ # time, the child would inherit the held lock and deadlock on
6217+ # its next ensure_running(). The at-fork handler reinits it.
6218+ cmd = textwrap .dedent ('''
6219+ import os, threading
6220+ from multiprocessing.resource_tracker import _resource_tracker
6221+
6222+ held = threading.Event()
6223+ release = threading.Event()
6224+ def hold():
6225+ with _resource_tracker._lock:
6226+ held.set()
6227+ release.wait()
6228+ t = threading.Thread(target=hold)
6229+ t.start()
6230+ held.wait()
6231+
6232+ pid = os.fork()
6233+ if pid == 0:
6234+ ok = _resource_tracker._lock.acquire(timeout=5.0)
6235+ os._exit(0 if ok else 1)
6236+
6237+ release.set()
6238+ t.join()
6239+ _, status = os.waitpid(pid, 0)
6240+ print(os.waitstatus_to_exitcode(status))
6241+ ''' )
6242+ rc , out , err = script_helper .assert_python_ok (
6243+ '-W' , 'ignore::DeprecationWarning' , '-c' , cmd )
6244+ self .assertEqual (out .strip (), b'0' ,
6245+ f"child failed to acquire lock: stderr={ err !r} " )
6246+
6247+ @only_run_in_forkserver_testsuite ("avoids redundant testing." )
6248+ def test_resource_tracker_safety_net_timeout (self ):
6249+ # gh-146313: When an mp.Process(fork) child holds the preserved
6250+ # fd and the parent calls _stop() without joining (simulating
6251+ # abnormal shutdown), the safety-net timeout should fire rather
6252+ # than deadlocking.
6253+ cmd = textwrap .dedent ('''
6254+ import multiprocessing as mp
6255+ import signal
6256+ from multiprocessing.resource_tracker import _resource_tracker
6257+
6258+ if __name__ == "__main__":
6259+ mp.set_start_method("fork")
6260+ _resource_tracker.ensure_running()
6261+ p = mp.Process(target=signal.pause)
6262+ p.start()
6263+ # Stop WITHOUT joining -- child still holds preserved fd
6264+ _resource_tracker._stop(wait_timeout=0.5)
6265+ print(_resource_tracker._waitpid_timed_out)
6266+ p.terminate()
6267+ p.join()
6268+ ''' )
6269+ rc , out , err = script_helper .assert_python_ok ('-c' , cmd )
6270+ self .assertEqual (out .strip (), b'True' ,
6271+ f"safety-net timeout did not fire: stderr={ err !r} " )
6272+
6273+
60966274class TestSimpleQueue (unittest .TestCase ):
60976275
60986276 @classmethod
0 commit comments