13
13
from anyio .abc import Process
14
14
from anyio .streams .file import FileReadStream , FileWriteStream
15
15
16
+ # Windows-specific imports for Job Objects
17
+ if sys .platform == "win32" :
18
+ import pywintypes
19
+ import win32api
20
+ import win32con
21
+ import win32job
22
+ else :
23
+ # Type stubs for non-Windows platforms
24
+ win32api = None
25
+ win32con = None
26
+ win32job = None
27
+ pywintypes = None
28
+
29
+ JobHandle = int
30
+
16
31
17
32
def get_windows_executable_command (command : str ) -> str :
18
33
"""
@@ -103,6 +118,11 @@ def kill(self) -> None:
103
118
"""Kill the subprocess immediately (alias for terminate)."""
104
119
self .terminate ()
105
120
121
+ @property
122
+ def pid (self ) -> int :
123
+ """Return the process ID."""
124
+ return self .popen .pid
125
+
106
126
107
127
# ------------------------
108
128
# Updated function
@@ -117,13 +137,16 @@ async def create_windows_process(
117
137
cwd : Path | str | None = None ,
118
138
) -> Process | FallbackProcess :
119
139
"""
120
- Creates a subprocess in a Windows-compatible way.
140
+ Creates a subprocess in a Windows-compatible way with Job Object support .
121
141
122
142
Attempt to use anyio's open_process for async subprocess creation.
123
143
In some cases this will throw NotImplementedError on Windows, e.g.
124
144
when using the SelectorEventLoop which does not support async subprocesses.
125
145
In that case, we fall back to using subprocess.Popen.
126
146
147
+ The process is automatically added to a Job Object to ensure all child
148
+ processes are terminated when the parent is terminated.
149
+
127
150
Args:
128
151
command (str): The executable to run
129
152
args (list[str]): List of command line arguments
@@ -132,8 +155,11 @@ async def create_windows_process(
132
155
cwd (Path | str | None): Working directory for the subprocess
133
156
134
157
Returns:
135
- FallbackProcess: Async-compatible subprocess with stdin and stdout streams
158
+ Process | FallbackProcess: Async-compatible subprocess with stdin and stdout streams
136
159
"""
160
+ job = _create_job_object ()
161
+ process = None
162
+
137
163
try :
138
164
# First try using anyio with Windows-specific flags to hide console window
139
165
process = await anyio .open_process (
@@ -146,10 +172,9 @@ async def create_windows_process(
146
172
stderr = errlog ,
147
173
cwd = cwd ,
148
174
)
149
- return process
150
175
except NotImplementedError :
151
- # Windows often doesn't support async subprocess creation, use fallback
152
- return await _create_windows_fallback_process (command , args , env , errlog , cwd )
176
+ # If Windows doesn't support async subprocess creation, use fallback
177
+ process = await _create_windows_fallback_process (command , args , env , errlog , cwd )
153
178
except Exception :
154
179
# Try again without creation flags
155
180
process = await anyio .open_process (
@@ -158,7 +183,9 @@ async def create_windows_process(
158
183
stderr = errlog ,
159
184
cwd = cwd ,
160
185
)
161
- return process
186
+
187
+ _maybe_assign_process_to_job (process , job )
188
+ return process
162
189
163
190
164
191
async def _create_windows_fallback_process (
@@ -185,8 +212,6 @@ async def _create_windows_fallback_process(
185
212
bufsize = 0 , # Unbuffered output
186
213
creationflags = getattr (subprocess , "CREATE_NO_WINDOW" , 0 ),
187
214
)
188
- return FallbackProcess (popen_obj )
189
-
190
215
except Exception :
191
216
# If creationflags failed, fallback without them
192
217
popen_obj = subprocess .Popen (
@@ -198,4 +223,86 @@ async def _create_windows_fallback_process(
198
223
cwd = cwd ,
199
224
bufsize = 0 ,
200
225
)
201
- return FallbackProcess (popen_obj )
226
+ process = FallbackProcess (popen_obj )
227
+ return process
228
+
229
+
230
+ def _create_job_object () -> int | None :
231
+ """
232
+ Create a Windows Job Object configured to terminate all processes when closed.
233
+ """
234
+ if sys .platform != "win32" or not win32job :
235
+ return None
236
+
237
+ try :
238
+ job = win32job .CreateJobObject (None , "" )
239
+ extended_info = win32job .QueryInformationJobObject (job , win32job .JobObjectExtendedLimitInformation )
240
+
241
+ # Set the job to terminate all processes when the handle is closed
242
+ extended_info ["BasicLimitInformation" ]["LimitFlags" ] |= win32job .JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
243
+ win32job .SetInformationJobObject (job , win32job .JobObjectExtendedLimitInformation , extended_info )
244
+ return job
245
+ except Exception :
246
+ # If job creation fails, return None
247
+ return None
248
+
249
+
250
+ def _maybe_assign_process_to_job (process : Process | FallbackProcess , job : JobHandle | None ) -> None :
251
+ """
252
+ Try to assign a process to a job object. If assignment fails
253
+ for any reason, the job handle is closed.
254
+ """
255
+ if not job :
256
+ return
257
+
258
+ if sys .platform != "win32" or not win32api or not win32con or not win32job :
259
+ return
260
+
261
+ try :
262
+ process_handle = win32api .OpenProcess (
263
+ win32con .PROCESS_SET_QUOTA | win32con .PROCESS_TERMINATE , False , process .pid
264
+ )
265
+ if not process_handle :
266
+ raise Exception ("Failed to open process handle" )
267
+
268
+ try :
269
+ win32job .AssignProcessToJobObject (job , process_handle )
270
+ process ._job_object = job
271
+ finally :
272
+ # Always close the process handle
273
+ win32api .CloseHandle (process_handle )
274
+ except Exception :
275
+ # If we can't assign to job, close it
276
+ if win32api :
277
+ win32api .CloseHandle (job )
278
+
279
+
280
+ async def terminate_windows_process_tree (process : Process | FallbackProcess ) -> None :
281
+ """
282
+ Terminate a process and all its children on Windows.
283
+
284
+ If the process has an associated job object, it will be terminated.
285
+ Otherwise, falls back to basic process termination.
286
+ """
287
+ if sys .platform != "win32" :
288
+ return
289
+
290
+ job = getattr (process , "_job_object" , None )
291
+ if job and win32job :
292
+ try :
293
+ win32job .TerminateJobObject (job , 1 )
294
+ except Exception :
295
+ # Job might already be terminated
296
+ pass
297
+ finally :
298
+ if win32api :
299
+ try :
300
+ win32api .CloseHandle (job )
301
+ except Exception :
302
+ pass
303
+
304
+ # Always try to terminate the process itself as well
305
+ try :
306
+ process .terminate ()
307
+ except Exception :
308
+ pass
0 commit comments