win_console_handler.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. """Script used to test os.kill on Windows, for issue #1220212
  2. This script is started as a subprocess in test_os and is used to test the
  3. CTRL_C_EVENT and CTRL_BREAK_EVENT signals, which requires a custom handler
  4. to be written into the kill target.
  5. See http://msdn.microsoft.com/en-us/library/ms685049%28v=VS.85%29.aspx for a
  6. similar example in C.
  7. """
  8. from ctypes import wintypes, WINFUNCTYPE
  9. import signal
  10. import ctypes
  11. import mmap
  12. import sys
  13. # Function prototype for the handler function. Returns BOOL, takes a DWORD.
  14. HandlerRoutine = WINFUNCTYPE(wintypes.BOOL, wintypes.DWORD)
  15. def _ctrl_handler(sig):
  16. """Handle a sig event and return 0 to terminate the process"""
  17. if sig == signal.CTRL_C_EVENT:
  18. pass
  19. elif sig == signal.CTRL_BREAK_EVENT:
  20. pass
  21. else:
  22. print("UNKNOWN EVENT")
  23. return 0
  24. ctrl_handler = HandlerRoutine(_ctrl_handler)
  25. SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
  26. SetConsoleCtrlHandler.argtypes = (HandlerRoutine, wintypes.BOOL)
  27. SetConsoleCtrlHandler.restype = wintypes.BOOL
  28. if __name__ == "__main__":
  29. # Add our console control handling function with value 1
  30. if not SetConsoleCtrlHandler(ctrl_handler, 1):
  31. print("Unable to add SetConsoleCtrlHandler")
  32. exit(-1)
  33. # Awake main process
  34. m = mmap.mmap(-1, 1, sys.argv[1])
  35. m[0] = 1
  36. # Do nothing but wait for the signal
  37. while True:
  38. pass