Skip to content

Instantly share code, notes, and snippets.

@justinmklam
Last active March 8, 2019 17:50
Show Gist options
  • Save justinmklam/afe430a7d7c5e59784734b648552e17f to your computer and use it in GitHub Desktop.
Save justinmklam/afe430a7d7c5e59784734b648552e17f to your computer and use it in GitHub Desktop.
Example code to launch a subprocess and terminate all spawned/child processes. For use when .kill() and .terminate() don't work.
# Source: https://stackoverflow.com/a/4791612
import os
import signal
import subprocess
# The os.setsid() is passed in the argument preexec_fn so
# it's run after the fork() and before exec() to run the shell.
pro = subprocess.Popen(cmd, stdout=subprocess.PIPE,
shell=True, preexec_fn=os.setsid)
os.killpg(os.getpgid(pro.pid), signal.SIGTERM) # Send the signal to all the process groups
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment