Search code examples
pythonsubprocesspopensigint

Sending a Ctrl+C SIGINT to sudoed C subprocess from python framework


I'm running a python subprocess using:

p = Popen(["sudo", "./a.out"])

where a.out is a C executable which runs continuously until a SIGINT or Ctrl+C signal is sent to it. I've had trouble with subprocess.Popen object functions such as send_signal() because Operation not permitted errors are raised due to the sudo nature of the executable. After this I tried to send a SIGINT to the subprocess via:

os.system(f"sudo kill -2 {p.pid}")

but this doesn't seem to target the process correctly. Running a quick sudo netstat -lpnt check shows the a.out process is still running on a pid which is different to the one which p.pid returned (usually by a few integers, i.e. p.pid returns 3031 but a.out is 3035). Anything that I've misunderstood?


Solution

  • You are actually getting pid of and killing sudo process (that forked your application process). Instead you should kill the whole process group with:

    import subprocess, os
    p = Popen(["sudo", "./a.out"])
    pgid = os.getpgid(p.pid)
    subprocess.check_output("sudo kill {}".format(pgid))
    

    or with the help of pkill:

    import subprocess
    p = Popen(["sudo", "./a.out"])
    subprocess.call(f"sudo pkill -2 -P {p.pid})