Killing the children with the parent

后端 未结 7 1531
孤城傲影
孤城傲影 2020-12-08 11:36

I have a program spawning and communicating with CPU heavy, unstable processes, not created by me. If my app crashes or is killed by SIGKILL, I want the subproc

7条回答
  •  星月不相逢
    2020-12-08 12:16

    Actually I found that your original approach worked just fine for me - here's the exact example code I tested with which worked:

    echoer.py

    #!/bin/env python
    
    import time
    import sys
    i = 0
    try:
        while True:
            i += 1
            print i
            time.sleep(1)
    except KeyboardInterrupt:
        print "\nechoer caught KeyboardInterrupt"
        exit(0)
    

    parentProc.py

    #!/bin/env python
    
    import ctypes
    import subprocess
    import time
    
    libc = ctypes.CDLL('/lib64/libc.so.6')
    PR_SET_PDEATHSIG = 1
    SIGINT = 2
    SIGTERM = 15
    
    def set_death_signal(signal):
        libc.prctl(PR_SET_PDEATHSIG, signal)
    
    def set_death_signal_int():
        set_death_signal(SIGINT)
    
    def set_death_signal_term():
        set_death_signal(SIGTERM)
    
    #subprocess.Popen(['./echoer.py'], preexec_fn=set_death_signal_term)
    subprocess.Popen(['./echoer.py'], preexec_fn=set_death_signal_int)
    time.sleep(1.5)
    print "parentProc exiting..."
    

提交回复
热议问题