From 4de973483e155a3cc51d184218bca399ab5460b0 Mon Sep 17 00:00:00 2001 From: Valentin Schneider Date: Tue, 12 Sep 2017 14:52:39 +0100 Subject: [PATCH] host: Add kill_children utility method This method is useful for killing the children spawned by Popen() calls with shell=True. For instance: proc = Popen('sleep 100', shell=True) proc.kill() This would spawn a shell task and that shell would spawn the sleep task. Issuing a kill to the Popen handle will only kill the shell task, and the sleep task will keep running. Using host.kill_children(proc.pid) will ensure all child tasks are killed. --- devlib/host.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/devlib/host.py b/devlib/host.py index 8c8a069..8062d24 100644 --- a/devlib/host.py +++ b/devlib/host.py @@ -14,6 +14,7 @@ # from glob import iglob import os +import signal import shutil import subprocess import logging @@ -24,6 +25,11 @@ from devlib.utils.misc import check_output PACKAGE_BIN_DIRECTORY = os.path.join(os.path.dirname(__file__), 'bin') +def kill_children(pid, signal=signal.SIGKILL): + with open('/proc/{0}/task/{0}/children'.format(pid), 'r') as fd: + for cpid in map(int, fd.read().strip().split()): + kill_children(cpid, signal) + os.kill(cpid, signal) class LocalConnection(object):