Reputation: 2784
Python 2.7, Ubuntu 16.04
We have a proprietary mathematical package we purchased that we use for calculations. We are trying to build a process that kills the subprocess of that package after running for 10 seconds.
The solution below kills the do_math()
function after 10 seconds as expected. However the solve
launches a sub process with it's own pid. So, doing a ps aux
shows that it runs under its own name, and not under the python
name.
Is there any way to track and kill a pid that has been launched this way in python?
def do_math():
status = solve() #launches the package
#Start function as a process
k = multiprocessing.Process(target=do_math)
k.start()
# Wait for 10 seconds or until process finishes
k.join(10)
# If thread is still active
if k.is_alive():
print k.pid
os.kill(k.pid, signal.SIGINT)
Upvotes: 0
Views: 66
Reputation: 365717
Assuming that the solve
function is doing something nasty that you can't change, there is no easy or clean way to do this.
One possibility is to spawn the child in its own group and then nuke the group… but that's not trivial to manage with multiprocessing
, and it may not even work depending on how solve
launches the grandchildren.
An even hackier way, but probably both easier and more likely to work, is to manually walk the child's process tree to find and kill any grandchildren either before or after killing the child. The simplest way to do that is probably a third-party library like psutil
. It would look something like this:
# Shortly after launching k
p = psutil.Process(k.pid)
# Later, right before killing k
for child in p.children():
p.send_signal(signal.SIGINT)
If you want to kill them after the child (I assume there's a reason you're sending SIGINT
instead of SIGTERM
, so this might matter), you'll want to copy p.children()
first before killing k
.
Upvotes: 1