Cannot correctly catch keyinterrupt in python script when calling "stress-ng"

39 Views Asked by At

I register signal in script and trying to catch SIGINT when I press ctrl + c. Everything is fine until I used subprocess module to call "stress-ng" tool. The terminal showed the script received SIGALRM when pressing ctrl + c. I don't know how to received SIGINT correctly when running "stress-ng" by python script.

#!/usr/bin/env python3
import signal
import shlex
from subprocess import Popen, PIPE

def signal_handler(sig, frame):
    print('You pressed Ctrl+C!')
    raise KeyboardInterrupt()

signal.signal(signal.SIGINT, signal_handler)
command = "stress-ng -c 0 -t 100 --metrics-brief -v --tz"
try:
    proc = Popen(
        shlex.split(command),
        shell=False,
        stdin=PIPE,
        stdout=PIPE,
        stderr=PIPE,
        close_fds=True,
        )
    (out, err) = proc.communicate()
    proc.wait()

except KeyboardInterrupt:
    print("Program aborted")

Here is my console output. enter image description here

I try to register SIGALRM and catch it, but it not work when I press ctrl + c.

0

There are 0 best solutions below