user2976718
user2976718

Reputation: 31

Pausing Python subprocesses from keyboard input without killing the subprocess

I'm working on a project to produce a shell in Python, and one important feature is the ability to pause and background a running subprocess. However the only methods I've found of pausing the subprocess appear to kill it instantly, so I can't resume it later. Our group has tried excepting KeyboardInterrupt:

try:
    process = subprocess.Popen(processName)
    process.communicate()
except KeyboardInterrupt:
    print "control character pressed"

and also using signals:

def signal_handler(signal,frame):
    print 'control character pressed'

signal.signal(signal.SIGINT, signal_handler)
process.communicate()

Another issue is that both of these only work when Ctrl-C is pressed, nothing else has any effect (I imagine this is why the subprocesses are being killed).

Upvotes: 3

Views: 578

Answers (1)

Jay Bosamiya
Jay Bosamiya

Reputation: 3229

The reason you have the process dying is because you are allowing the Ctrl+C to reach the subprocess. If you were to use the parameter preexec_fn = os.setpgrp, as part of the Popen call, then the the child is set to be in a different process group from the parent.

Ctrl+C sends a SIGINT to the complete process group, but since the child is in a different process group, it doesn't receive the SIGINT and thus doesn't die.

After that, the send_signal() function can be used to send a SIGSTOP to the child process whenever you want to pause it, and a SIGCONT to resume it.

Upvotes: 1

Related Questions