win_interrupt.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. """Use a Windows event to interrupt a child process like SIGINT.
  2. The child needs to explicitly listen for this - see
  3. ipykernel.parentpoller.ParentPollerWindows for a Python implementation.
  4. """
  5. import ctypes
  6. def create_interrupt_event():
  7. """Create an interrupt event handle.
  8. The parent process should call this to create the
  9. interrupt event that is passed to the child process. It should store
  10. this handle and use it with ``send_interrupt`` to interrupt the child
  11. process.
  12. """
  13. # Create a security attributes struct that permits inheritance of the
  14. # handle by new processes.
  15. # FIXME: We can clean up this mess by requiring pywin32 for IPython.
  16. class SECURITY_ATTRIBUTES(ctypes.Structure):
  17. _fields_ = [ ("nLength", ctypes.c_int),
  18. ("lpSecurityDescriptor", ctypes.c_void_p),
  19. ("bInheritHandle", ctypes.c_int) ]
  20. sa = SECURITY_ATTRIBUTES()
  21. sa_p = ctypes.pointer(sa)
  22. sa.nLength = ctypes.sizeof(SECURITY_ATTRIBUTES)
  23. sa.lpSecurityDescriptor = 0
  24. sa.bInheritHandle = 1
  25. return ctypes.windll.kernel32.CreateEventA(
  26. sa_p, # lpEventAttributes
  27. False, # bManualReset
  28. False, # bInitialState
  29. '') # lpName
  30. def send_interrupt(interrupt_handle):
  31. """ Sends an interrupt event using the specified handle.
  32. """
  33. ctypes.windll.kernel32.SetEvent(interrupt_handle)