How to pass SIGINT to child process with Python subprocess.Popen() using shell = true

Mike picture Mike · Jun 18, 2015 · Viewed 8k times · Source

I am currently trying to write (Python 2.7.3) kind of a wrapper for GDB, which will allow me to dynamically switch from scripted input to interactive communication with GDB.

So far I use

self.process = subprocess.Popen(["gdb vuln"], stdin = subprocess.PIPE,  shell = True)

to start gdb within my script. (vuln is the binary I want to examine)

Since a key feature of gdb is to pause the execution of the attached process and allow the user to inspect registers and memory on receiving SIGINT (STRG+C) I do need some way to pass a SIGINT signal to it.

Neither

self.process.send_signal(signal.SIGINT)

nor

os.kill(self.process.pid, signal.SIGINT)

or

os.killpg(self.process.pid, signal.SIGINT)

work for me.

When I use one of these functions there is no response. I suppose this problem arises from the use of shell=True. However, at this point I am really out of ideas. Even my old friend Google couldn't really help me out this time, so maybe you can help me. Thank's in advance.

Cheers, Mike

Answer

sirex picture sirex · May 25, 2018

Here is what worked for me:

import signal
import subprocess

try:
    p = subprocess.Popen(...)
    p.wait()
except KeyboardInterrupt:
    p.send_signal(signal.SIGINT)
    p.wait()