Skip to content

Commit

Permalink
Ensure all child processes are terminated
Browse files Browse the repository at this point in the history
  • Loading branch information
weilycoder committed Dec 4, 2024
1 parent 0942353 commit 55c57f4
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 3 deletions.
20 changes: 19 additions & 1 deletion cyaron/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import re
import subprocess
import tempfile
import psutil
from typing import Union, overload, Optional, List
from io import IOBase
from . import log
Expand Down Expand Up @@ -227,6 +228,22 @@ def __clear(self, file: IOBase, pos: int = 0):
self.is_first_char[file] = True
file.seek(pos)

@staticmethod
def _kill_process_and_children(pid: int):
try:
parent = psutil.Process(pid)
while True:
children = parent.children()
if not children:
break
for child in children:
IO._kill_process_and_children(child.pid)
parent.kill()
except psutil.NoSuchProcess:
pass
except psutil.AccessDenied:
pass

def input_write(self, *args, **kwargs):
"""
Write every element in *args into the input file. Splits with `separator`.
Expand Down Expand Up @@ -293,7 +310,8 @@ def output_gen(
try:
output, _ = proc.communicate(timeout=time_limit)
except subprocess.TimeoutExpired:
proc.kill()
# proc.kill() # didn't work because `shell=True`.
self._kill_process_and_children(proc.pid)
raise
else:
if replace_EOL:
Expand Down
34 changes: 32 additions & 2 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ readme = "README.md"
python = ">=3.6"
xeger = "^0.4.0"
colorful = "^0.5.6"
psutil = "^6.1.0"


[build-system]
Expand Down

0 comments on commit 55c57f4

Please sign in to comment.