1212 "inspect" ,
1313 "math" ,
1414 "numbers" ,
15+ "pathlib" ,
1516 "secrets" ,
1617 "types" ,
1718 "warnings" ,
2526import logging
2627import math
2728import os
29+ import pathlib
2830import secrets
2931import stat
3032import sys
@@ -1062,6 +1064,7 @@ def acquire(
10621064 raise
10631065
10641066 def _raise_if_inherited (self ) -> None :
1067+ ensure_current_process ()
10651068 if self ._creator_pid != os .getpid (): # pragma: forked child
10661069 msg = f"{ type (self ).__name__ } on { self .lock_file } was inherited across fork; construct a new instance"
10671070 raise RuntimeError (msg )
@@ -1459,6 +1462,7 @@ def release(self, force: bool = False) -> None: # ruff:ignore[boolean-type-hint
14591462 running, and a ``thread_local=False`` lock while any other thread runs.
14601463
14611464 """
1465+ ensure_current_process ()
14621466 release_snapshot : tuple [int , int ] | None = None
14631467 transition_entered = False
14641468 try : # ruff:ignore[too-many-statements-in-try-clause] # gate-entry signals and release failures need separate recovery
@@ -1866,6 +1870,8 @@ def _mark_descriptor_released(self) -> None:
18661870 def _reset_after_fork_in_child (self ) -> None : # pragma: forked child
18671871 # fork copies the lock in whatever state the parent's threads left it, so give the child an unheld one.
18681872 self ._transition_lock = RLock ()
1873+ # A different PID namespace may give the child the same numeric PID.
1874+ self ._creator_pid = - 1
18691875 if isinstance (self ._context , ThreadLocalFileContext ):
18701876 self ._thread_holds .clear ()
18711877 self ._thread_pending .clear ()
@@ -2208,6 +2214,16 @@ class _OwnedDescriptor:
22082214 inode : int | None
22092215
22102216
2217+ def _pid_namespace () -> tuple [int , int ] | None :
2218+ if sys .platform not in {"linux" , "android" }: # pragma: linux no cover # pragma: android no cover
2219+ return None
2220+ try :
2221+ namespace = pathlib .Path ("/proc/self/ns/pid" ).stat ()
2222+ except OSError :
2223+ return None
2224+ return namespace .st_dev , namespace .st_ino
2225+
2226+
22112227class _ForkState :
22122228 def __init__ (self ) -> None :
22132229 self .gate = Condition (RLock ())
@@ -2221,7 +2237,7 @@ def __init__(self) -> None:
22212237 self .pinned_classes : dict [int , list [tuple [_ForkResettableClass , ...]]] = {}
22222238 self .provisional_descriptor_tokens : dict [int , list [tuple [int , ...]]] = {}
22232239 self .undrained_forks : set [int ] = set ()
2224- self .pid = os .getpid ()
2240+ self .process_identity = os .getpid (), _pid_namespace ()
22252241
22262242 def reset_synchronization (self ) -> None : # pragma: forked child
22272243 self .gate = Condition (RLock ())
@@ -2258,7 +2274,7 @@ def _register_fork_hooks() -> None:
22582274 _REGISTER_AT_FORK ( # pragma: needs fork
22592275 before = _pin_fork_objects ,
22602276 after_in_parent = _resume_parent_after_fork ,
2261- after_in_child = _reset_child_after_fork ,
2277+ after_in_child = partial ( _reset_child_after_fork , from_hook = True ) ,
22622278 )
22632279
22642280
@@ -2349,21 +2365,25 @@ def ensure_current_process() -> None:
23492365 _reset_child_after_fork ()
23502366
23512367
2352- def _reset_child_after_fork () -> None : # pragma: forked child
2353- if (pid := os .getpid ()) == _FORK_STATE .pid :
2354- return
2368+ def _reset_child_after_fork (* , from_hook : bool = False ) -> None : # pragma: forked child
2369+ pid = os .getpid ()
23552370 thread_id = get_ident ()
2371+ if pid == _FORK_STATE .process_identity [0 ]:
2372+ if thread_id not in _FORK_STATE .fork_owner_depths :
2373+ return
2374+ if not from_hook :
2375+ previous = _FORK_STATE .process_identity [1 ]
2376+ if previous is None or (current := _pid_namespace ()) is None or current == previous :
2377+ return
23562378 if thread_id in _FORK_STATE .undrained_forks :
23572379 os .write (2 , b"filelock: fork child exits: another thread was still changing a lock's descriptor ownership\n " )
23582380 os ._exit (70 ) # the inherited descriptor state is unsafe; the parent continues
23592381 pinned_objects = _FORK_STATE .pinned_objects .get (thread_id , [()])[- 1 ]
23602382 pinned_classes = _FORK_STATE .pinned_classes .get (thread_id , [()])[- 1 ]
2361- descriptors : list [_OwnedDescriptor ] = []
2362- for token , descriptor in tuple (_OWNED_DESCRIPTORS .items ()):
2363- if descriptor .creator_pid != pid :
2364- descriptors .append (_OWNED_DESCRIPTORS .pop (token ))
2383+ descriptors = list (_OWNED_DESCRIPTORS .values ())
2384+ _OWNED_DESCRIPTORS .clear ()
23652385 _FORK_STATE .reset_synchronization ()
2366- _FORK_STATE .pid = pid
2386+ _FORK_STATE .process_identity = pid , _pid_namespace ()
23672387 _INIT_PARAMETER_MODELS .clear ()
23682388 _detach_child_state (descriptors , pinned_objects , pinned_classes )
23692389
0 commit comments