Terminating a process and its subprocesses from python

published May 22, 2015 12:45   by admin ( last modified May 22, 2015 12:50 )

I'm testing a python server from a python test script. The server reads a config file on startup and I want to test that it actually works. So I want the script to test the server as if it were run from the command line. When run from the command line, the server can be terminated by typing Ctrl-c.

The server starts a child process from inside itself. Problem is, if I start the server with subprocess, and then send the kill/terminate signal to it via subprocess, the server's child process keeps running.

The trick is to assign a new process group to the server, separate from the testing script. In this way the os module can issue a "killpg" command that takes care of terminating the server and its child processes, without killing the testing script.

import subprocess
import os
import signal

p=subprocess.Popen(your_command, preexec_fn=os.setsid, shell=True) 
os.killpg(os.getpgid(p.pid), signal.SIGTERM) 



Found this solution on Stackoverflow:

To handle the general problem:
p=subprocess.Popen(your_command, preexec_fn=os.setsid) 
os.killpg(os.getpgid(p.pid), 15) 
setsid will run the program in a new session, thus assigning a new process group to it and its children. calling os.killpg on it thus won't bring down your own python process also.


Read more: Link - unix - Killing a subprocess including its children from python - Stack Overflow