ealeon ealeon - 1 year ago 76
Python Question

subprocess Popen: signal not propagating

execute_sleep.py

import os
import time
import subprocess

sleep_script = 'sleep_forever.py'
child = subprocess.Popen(sleep_script,
shell=True,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)

subout = child.communicate()[0]
print subout
rc = child.returncode


sleep_forever.py

#!/usr/bin/python
import time

while True:
time.sleep(1)


When I run execute_sleep.py and then
kill -TERM -- -<pid of execute_sleep.py>
,
execute_sleep.py dies but sleep_forever.py keeps running.

What can I do so that when execute_sleep.py gets signal, it propagates down to sleep_forever.py?

Do any of these options block signals?


  • shell=True

  • close_fds=True

  • the use of
    subprocess.PIPE


Answer Source

You need to handle the signal, otherwise you are creating orphans (sleep_script processes). So that when the signal to terminate the father process is caught it propagates to child processes before.

def handler(signum, frame):
    functionToKillSleeper(pidtokill)


signal.signal(signal.SIGTERM, handler)

Note that SIGKILL cannot be caught.

So you will need to SIGINT or SIGTERM the father process in order for the signal to be handled, otherwise your problem will remain.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download