@@ -480,6 +480,9 @@ def _ungrab_devices(self):
480480 log .debug ("failed to ungrab device" , exc_info = True )
481481
482482 def start (self ):
483+ # Exception note: cancel() will eventually by called when the machine
484+ # reconnect machine is pressed, or when the machine is changed.
485+ # Therefore, cancel() does not need to be called in the except block.
483486 try :
484487 self ._grab_devices ()
485488 self ._device_thread_read_pipe , self ._device_thread_write_pipe = os .pipe ()
@@ -498,17 +501,37 @@ def start(self):
498501 def cancel (self ):
499502 # Write some arbitrary data to the pipe to signal the _run thread to stop
500503 if self ._device_thread_write_pipe is not None :
501- os .write (self ._device_thread_write_pipe , b"a" )
504+ try :
505+ os .write (self ._device_thread_write_pipe , b"a" )
506+ except Exception :
507+ log .warning ("failed to write to device thread pipe" , exc_info = True )
502508 if self ._device_thread is not None :
503- self ._device_thread .join ()
504- self ._device_thread = None
509+ try :
510+ self ._device_thread .join ()
511+ except Exception :
512+ log .warning ("failed to join device thread" , exc_info = True )
513+ self ._device_thread = None
514+ try :
515+ self ._ungrab_devices ()
516+ except Exception :
517+ log .warning ("failed to ungrab devices" , exc_info = True )
518+ try :
519+ self ._selector .close ()
520+ except Exception :
521+ log .warning ("failed to close selector" , exec_info = True )
505522
506523 if self ._device_thread_read_pipe is not None :
507- self ._selector .unregister (self ._device_thread_read_pipe )
508- os .close (self ._device_thread_read_pipe )
524+ try :
525+ os .close (self ._device_thread_read_pipe )
526+ except Exception :
527+ log .warning ("failed to close device thread read pipe" , exc_info = True )
528+ self ._device_thread_read_pipe = None
509529 if self ._device_thread_write_pipe is not None :
510- os .close (self ._device_thread_write_pipe )
511- self ._selector .close ()
530+ try :
531+ os .close (self ._device_thread_write_pipe )
532+ except Exception :
533+ log .warning ("failed to close device thread write pipe" , exc_info = True )
534+ self ._device_thread_write_pipe = None
512535
513536 self ._running = False
514537
0 commit comments