Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 765
David Froger Avatar asked Apr 13 '26 06:04

David Froger


1 Answers

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.

like image 79
Yann Vernier Avatar answered Apr 14 '26 18:04

Yann Vernier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!