@@ -748,6 +748,7 @@ class BaseChildWatcher(AbstractChildWatcher):
748748
749749 def __init__ (self ):
750750 self ._loop = None
751+ self ._callbacks = {}
751752
752753 def close (self ):
753754 self .attach_loop (None )
@@ -761,6 +762,12 @@ def _do_waitpid_all(self):
761762 def attach_loop (self , loop ):
762763 assert loop is None or isinstance (loop , events .AbstractEventLoop )
763764
765+ if self ._loop is not None and loop is None and self ._callbacks :
766+ warnings .warn (
767+ 'A loop is being detached '
768+ 'from a child watcher with pending handlers' ,
769+ RuntimeWarning )
770+
764771 if self ._loop is not None :
765772 self ._loop .remove_signal_handler (signal .SIGCHLD )
766773
@@ -809,10 +816,6 @@ class SafeChildWatcher(BaseChildWatcher):
809816 big number of children (O(n) each time SIGCHLD is raised)
810817 """
811818
812- def __init__ (self ):
813- super ().__init__ ()
814- self ._callbacks = {}
815-
816819 def close (self ):
817820 self ._callbacks .clear ()
818821 super ().close ()
@@ -824,6 +827,11 @@ def __exit__(self, a, b, c):
824827 pass
825828
826829 def add_child_handler (self , pid , callback , * args ):
830+ if self ._loop is None :
831+ raise RuntimeError (
832+ "Cannot add child handler, "
833+ "the child watcher does not have a loop attached" )
834+
827835 self ._callbacks [pid ] = (callback , args )
828836
829837 # Prevent a race condition in case the child is already terminated.
@@ -888,7 +896,6 @@ class FastChildWatcher(BaseChildWatcher):
888896 """
889897 def __init__ (self ):
890898 super ().__init__ ()
891- self ._callbacks = {}
892899 self ._lock = threading .Lock ()
893900 self ._zombies = {}
894901 self ._forks = 0
@@ -920,6 +927,12 @@ def __exit__(self, a, b, c):
920927
921928 def add_child_handler (self , pid , callback , * args ):
922929 assert self ._forks , "Must use the context manager"
930+
931+ if self ._loop is None :
932+ raise RuntimeError (
933+ "Cannot add child handler, "
934+ "the child watcher does not have a loop attached" )
935+
923936 with self ._lock :
924937 try :
925938 returncode = self ._zombies .pop (pid )
0 commit comments