linux - Python SIGTERM handler is not activated in subprocess -
i want gracefully release expensive scheme resource in code event handler. problem event handler registered in forked sub-process (yes, have set event handler there in sub-process, since resource allocated after fork) , want sub-processes terminate when parent process dies. however, code not work expectation.
here runnable example:
import time import os import signal prctl=none # prctl libc def getprctl(): global prctl if prctl none: import ctypes prctl = ctypes.cdll("libc.so.6")["prctl"] homecoming prctl def diewithparent(): prctl = getprctl() prctl(1, signal.sigterm) # 1 = pr_set_pdeathsig def foo(): print "in foo." def handler(signo, frame): print "handler activated." signal.signal(signal.sigterm, handler) time.sleep(10) # in case sub-process terminates first. if __name__ == '__main__': diewithparent() pid = os.fork() if 0 == pid: foo() else: print "subprocess spawned." print "dying..." the code following:
instruct os turn parent die signal sigterm; fork sub-process; if kid process, register signal handler , wait parent's termination.on platform, output is
$ python main.py in foo. subprocess spawned. dying... it seems handler not activated.
anything wrong code or understanding?
configuration on box is
2.6.18-238.el5 x86_64 python 2.6
any hints highly appreciate, give thanks you!
from prctl
pr_set_pdeathsig (since linux 2.1.57) set parent process death signal of calling process arg2 (either signal value in range 1..maxsig, or 0 clear). signal calling process when parent dies. this value cleared kid of fork(2) , (since linux 2.4.36 / 2.6.23) when executing set-user-id or set-group-id binary.
so ensure parent dies it's parent, nil kid process.
if add:
diewithparent() after fork behaves correctly
python linux libc
No comments:
Post a Comment