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
@@ -1060,6 +1062,7 @@ def acquire(
10601062 raise
10611063
10621064 def _raise_if_inherited (self ) -> None :
1065+ ensure_current_process ()
10631066 if self ._creator_pid != os .getpid (): # pragma: forked child
10641067 msg = f"{ type (self ).__name__ } on { self .lock_file } was inherited across fork; construct a new instance"
10651068 raise RuntimeError (msg )
@@ -1454,6 +1457,7 @@ def release(self, force: bool = False) -> None: # ruff:ignore[boolean-type-hint
14541457 running, and a ``thread_local=False`` lock while any other thread runs.
14551458
14561459 """
1460+ ensure_current_process ()
14571461 release_snapshot : tuple [int , int ] | None = None
14581462 transition_entered = False
14591463 try : # ruff:ignore[too-many-statements-in-try-clause] # gate-entry signals and release failures need separate recovery
@@ -1864,6 +1868,8 @@ def _mark_descriptor_released(self) -> None:
18641868 def _reset_after_fork_in_child (self ) -> None : # pragma: forked child
18651869 # fork copies the lock in whatever state the parent's threads left it, so give the child an unheld one.
18661870 self ._transition_lock = RLock ()
1871+ # A different PID namespace may give the child the same numeric PID.
1872+ self ._creator_pid = - 1
18671873 if isinstance (self ._context , ThreadLocalFileContext ):
18681874 self ._thread_holds .clear ()
18691875 self ._thread_pending .clear ()
@@ -2201,6 +2207,16 @@ class _OwnedDescriptor:
22012207 inode : int | None
22022208
22032209
2210+ def _pid_namespace () -> tuple [int , int ] | None :
2211+ if sys .platform not in {"linux" , "android" }: # pragma: linux no cover # pragma: android no cover
2212+ return None
2213+ try :
2214+ namespace = pathlib .Path ("/proc/self/ns/pid" ).stat ()
2215+ except OSError :
2216+ return None
2217+ return namespace .st_dev , namespace .st_ino
2218+
2219+
22042220class _ForkState :
22052221 def __init__ (self ) -> None :
22062222 self .gate = Condition (RLock ())
@@ -2214,7 +2230,7 @@ def __init__(self) -> None:
22142230 self .pinned_classes : dict [int , list [tuple [_ForkResettableClass , ...]]] = {}
22152231 self .provisional_descriptor_tokens : dict [int , list [tuple [int , ...]]] = {}
22162232 self .undrained_forks : set [int ] = set ()
2217- self .pid = os .getpid ()
2233+ self .process_identity = os .getpid (), _pid_namespace ()
22182234
22192235 def reset_synchronization (self ) -> None : # pragma: forked child
22202236 self .gate = Condition (RLock ())
@@ -2251,7 +2267,7 @@ def _register_fork_hooks() -> None:
22512267 _REGISTER_AT_FORK ( # pragma: needs fork
22522268 before = _pin_fork_objects ,
22532269 after_in_parent = _resume_parent_after_fork ,
2254- after_in_child = _reset_child_after_fork ,
2270+ after_in_child = partial ( _reset_child_after_fork , from_hook = True ) ,
22552271 )
22562272
22572273
@@ -2342,21 +2358,25 @@ def ensure_current_process() -> None:
23422358 _reset_child_after_fork ()
23432359
23442360
2345- def _reset_child_after_fork () -> None : # pragma: forked child
2346- if (pid := os .getpid ()) == _FORK_STATE .pid :
2347- return
2361+ def _reset_child_after_fork (* , from_hook : bool = False ) -> None : # pragma: forked child
2362+ pid = os .getpid ()
23482363 thread_id = get_ident ()
2364+ if pid == _FORK_STATE .process_identity [0 ]:
2365+ if thread_id not in _FORK_STATE .fork_owner_depths :
2366+ return
2367+ if not from_hook :
2368+ previous = _FORK_STATE .process_identity [1 ]
2369+ if previous is None or (current := _pid_namespace ()) is None or current == previous :
2370+ return
23492371 if thread_id in _FORK_STATE .undrained_forks :
23502372 os .write (2 , b"filelock: fork child exits: another thread was still changing a lock's descriptor ownership\n " )
23512373 os ._exit (70 ) # the inherited descriptor state is unsafe; the parent continues
23522374 pinned_objects = _FORK_STATE .pinned_objects .get (thread_id , [()])[- 1 ]
23532375 pinned_classes = _FORK_STATE .pinned_classes .get (thread_id , [()])[- 1 ]
2354- descriptors : list [_OwnedDescriptor ] = []
2355- for token , descriptor in tuple (_OWNED_DESCRIPTORS .items ()):
2356- if descriptor .creator_pid != pid :
2357- descriptors .append (_OWNED_DESCRIPTORS .pop (token ))
2376+ descriptors = list (_OWNED_DESCRIPTORS .values ())
2377+ _OWNED_DESCRIPTORS .clear ()
23582378 _FORK_STATE .reset_synchronization ()
2359- _FORK_STATE .pid = pid
2379+ _FORK_STATE .process_identity = pid , _pid_namespace ()
23602380 _INIT_PARAMETER_MODELS .clear ()
23612381 _detach_child_state (descriptors , pinned_objects , pinned_classes )
23622382
0 commit comments