Debian Codegraph @

jupyter_client/win_interrupt.py

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