Does Python always raise an exception if you do Ctrl+C when a subprocess is executing?

Question:

Given the following code:

try:
  subprocess.Popen(ExternalProcess, stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True).communicate()
except KeyboardInterrupt:
  exit(0)

If during the execution of ExternalProcess(which is not a python script) one presses the Ctrl+C command, what exactly is going on?

Can I be sure for a 100% that in this scope, if I press the Ctrl+C, it will always get into the ‘except’ even if it happens during the execution of ExternalProcess?

Or it depends on how the external process deals with it?

Asked By: izac89

||

Answers:

As far as I understand, once you fork/exec a process, it inherits the parent’s process group. That means, that SIGINT (which is the result of Ctrl+C and the cause of KeyboardInterrupt) will be sent to both the child and the parent.

Here is an example:

File a.py:

import subprocess

try:
    subprocess.Popen("python b.py".split()).communicate()
except KeyboardInterrupt:
    print "a.py got ctrl-c"

File b.py

try:
    while True: pass
except KeyboardInterrupt:
    print "b.py got ctrl-c"

Now you run it and stop:

> python a.py
^Cb.py got ctrl-c
a.py got ctrl-c
Answered By: bereal

I assume you are using a Unix variant in my answer. I have no deeper knowledge about the Windows world.

If everything is configured normally, then the C-c will be interpreted by the terminal (xterm, gnome-terminal, …). This terminal will send a SIGINT (see kill -l to find out what your system’s number for this is, typically it is 2) to all processes of the processgroup attached to the tty device associated with this terminal. That is either the shell or the program the shell started (and all its children because process groups get inherited).

A child can, however, leave its process group voluntarily and create a new one. Daemon processes typically do this to avoid being killed accidentally by a Ctrl-C pressed in the father program.

Answered By: Alfe
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.