Skip to content

Commit e01dd4c

Browse files
committed
Refactor process killing
1 parent bccf676 commit e01dd4c

File tree

1 file changed

+22
-20
lines changed

1 file changed

+22
-20
lines changed

command_runner/__init__.py

+22-20
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,26 @@ def kill_childs_mod(
148148
sig = signal.SIGTERM
149149
### END COMMAND_RUNNER MOD
150150

151+
def _process_killer(process, # type: Union[subprocess.Popen, psutil.Process]
152+
sig, # type: signal.valid_signals
153+
soft_kill # type: bool
154+
):
155+
# (...) -> None
156+
"""
157+
Simple abstract process killer that works with signals in order to avoid reused PID race conditions
158+
and can prefers using terminate than kill
159+
"""
160+
if sig:
161+
try:
162+
process.send_signal(sig)
163+
except psutil.NoSuchProcess:
164+
pass
165+
else:
166+
if soft_kill:
167+
process.terminate()
168+
else:
169+
process.kill()
170+
151171
try:
152172
parent = psutil.Process(pid if pid is not None else os.getpid())
153173
except psutil.NoSuchProcess:
@@ -157,28 +177,10 @@ def kill_childs_mod(
157177
return False
158178

159179
for child in parent.children(recursive=True):
160-
if sig:
161-
try:
162-
child.send_signal(sig)
163-
except psutil.NoSuchProcess:
164-
pass
165-
else:
166-
if soft_kill:
167-
child.terminate()
168-
else:
169-
child.kill()
180+
_process_killer(child, sig, soft_kill)
170181

171182
if itself:
172-
if sig:
173-
try:
174-
parent.send_signal(sig)
175-
except psutil.NoSuchProcess:
176-
pass
177-
else:
178-
if soft_kill:
179-
parent.terminate()
180-
else:
181-
parent.kill()
183+
_process_killer(parent, sig, soft_kill)
182184
return True
183185

184186

0 commit comments

Comments
 (0)