Source

subproc_handling / sigterm.py

Full commit
"""
A SIGTERM is not forwarded to child processes if you send it into a
subprocess.

``proc.send_signal(signal.SIGTERM)`` is equivalent to ``proc.terminate()``.

Works on:

- Linux
- OS X
- Windows?

"""
import signal
import subprocess
import sys
import time


def parent():
    proc = subprocess.Popen(['python', 'sigterm.py', 'child'])

    def handler(signum, frame):
        # Uncomment these lines to see that "sig" is not forwarded
        # automatically.
        print('parent received SIGTERM')
        proc.send_signal(signal.SIGTERM)
        # proc.terminate()

        print('parent waiting for child')
        proc.wait()
        print('parent terminating')
        sys.exit(0)

    signal.signal(signal.SIGTERM, handler)
    time.sleep(60)


def child():
    def handler(signum, frame):
        print('child terminating')
        sys.exit(0)

    signal.signal(signal.SIGTERM, handler)
    time.sleep(60)


if __name__ == '__main__':
    if len(sys.argv) == 1:
        proc = subprocess.Popen(['python', 'sigterm.py', 'parent'])
        time.sleep(1)
        print('Sending SIGTERM to parent')
        proc.send_signal(signal.SIGTERM)
        # proc.terminate()
        print('Waiting for parent')
        proc.wait()
    elif sys.argv[1] == 'parent':
        parent()
    elif sys.argv[1] == 'child':
        child()