@@ -746,6 +746,7 @@ class BaseChildWatcher(AbstractChildWatcher):
746746
747747 def __init__ (self ):
748748 self ._loop = None
749+ self ._callbacks = {}
749750
750751 def close (self ):
751752 self .attach_loop (None )
@@ -759,6 +760,12 @@ def _do_waitpid_all(self):
759760 def attach_loop (self , loop ):
760761 assert loop is None or isinstance (loop , events .AbstractEventLoop )
761762
763+ if self ._loop is not None and loop is None and self ._callbacks :
764+ warnings .warn (
765+ 'A loop is being detached '
766+ 'from a child watcher with pending handlers' ,
767+ RuntimeWarning )
768+
762769 if self ._loop is not None :
763770 self ._loop .remove_signal_handler (signal .SIGCHLD )
764771
@@ -807,10 +814,6 @@ class SafeChildWatcher(BaseChildWatcher):
807814 big number of children (O(n) each time SIGCHLD is raised)
808815 """
809816
810- def __init__ (self ):
811- super ().__init__ ()
812- self ._callbacks = {}
813-
814817 def close (self ):
815818 self ._callbacks .clear ()
816819 super ().close ()
@@ -822,6 +825,11 @@ def __exit__(self, a, b, c):
822825 pass
823826
824827 def add_child_handler (self , pid , callback , * args ):
828+ if self ._loop is None :
829+ raise RuntimeError (
830+ "Cannot add child handler, "
831+ "the child watcher does not have a loop attached" )
832+
825833 self ._callbacks [pid ] = (callback , args )
826834
827835 # Prevent a race condition in case the child is already terminated.
@@ -886,7 +894,6 @@ class FastChildWatcher(BaseChildWatcher):
886894 """
887895 def __init__ (self ):
888896 super ().__init__ ()
889- self ._callbacks = {}
890897 self ._lock = threading .Lock ()
891898 self ._zombies = {}
892899 self ._forks = 0
@@ -918,6 +925,12 @@ def __exit__(self, a, b, c):
918925
919926 def add_child_handler (self , pid , callback , * args ):
920927 assert self ._forks , "Must use the context manager"
928+
929+ if self ._loop is None :
930+ raise RuntimeError (
931+ "Cannot add child handler, "
932+ "the child watcher does not have a loop attached" )
933+
921934 with self ._lock :
922935 try :
923936 returncode = self ._zombies .pop (pid )
0 commit comments