Skip to content

Commit 55c57f4

Browse files
committed
Ensure all child processes are terminated
1 parent 0942353 commit 55c57f4

File tree

3 files changed

+52
-3
lines changed

3 files changed

+52
-3
lines changed

cyaron/io.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import re
1010
import subprocess
1111
import tempfile
12+
import psutil
1213
from typing import Union, overload, Optional, List
1314
from io import IOBase
1415
from . import log
@@ -227,6 +228,22 @@ def __clear(self, file: IOBase, pos: int = 0):
227228
self.is_first_char[file] = True
228229
file.seek(pos)
229230

231+
@staticmethod
232+
def _kill_process_and_children(pid: int):
233+
try:
234+
parent = psutil.Process(pid)
235+
while True:
236+
children = parent.children()
237+
if not children:
238+
break
239+
for child in children:
240+
IO._kill_process_and_children(child.pid)
241+
parent.kill()
242+
except psutil.NoSuchProcess:
243+
pass
244+
except psutil.AccessDenied:
245+
pass
246+
230247
def input_write(self, *args, **kwargs):
231248
"""
232249
Write every element in *args into the input file. Splits with `separator`.
@@ -293,7 +310,8 @@ def output_gen(
293310
try:
294311
output, _ = proc.communicate(timeout=time_limit)
295312
except subprocess.TimeoutExpired:
296-
proc.kill()
313+
# proc.kill() # didn't work because `shell=True`.
314+
self._kill_process_and_children(proc.pid)
297315
raise
298316
else:
299317
if replace_EOL:

poetry.lock

Lines changed: 32 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ readme = "README.md"
1010
python = ">=3.6"
1111
xeger = "^0.4.0"
1212
colorful = "^0.5.6"
13+
psutil = "^6.1.0"
1314

1415

1516
[build-system]

0 commit comments

Comments
 (0)