David Froger
David Froger

Reputation: 665

python forward SIGINT to subprocess

Here is a simple Python script that spawn a process:

import subprocess
import os

subprocess.run(['ping', '-i', '30', 'google.fr'],
               preexec_fn=lambda : os.setpgrp())

When I kill -TERM <python-pid>, it stops the python process, but the ping process continue running: that's what I was expecting.

But when I kill -INT <python-pid>, both python and ping processes are stopped. This is different from CTRL-V which send the SIGINT to the process group, not just the process. Anyway, the setpgrp make the ping process become the leader of its own process group.

So I suppose that somewhere in Python code, SIGINT is sent ot the ping child, but SIGTERM is not, but where is this code, and where is it documented?

Edit: I'm running Python 3.6 on Debian 9.

Upvotes: 3

Views: 1627

Answers (1)

Yann Vernier
Yann Vernier

Reputation: 15877

The code is in subprocess.run, the function you called. SIGINT gets converted into a KeyboardInterrupt exception, which is handled by an except clause that calls process.kill(). You could implement different handling of SIGINT using the signal module. Notably, kill doesn't send SIGINT but sends SIGKILL, so the subprocess does not get a chance to do similar handling with this default cleanup.

Upvotes: 4

Related Questions