[转]Linux下让父进程结束后,子进程自动结束
原文:http://xiaoxia.org/2012/03/05/prctl/
在多进程编程的时候,经常会遇到这样的情况。父进程创建了一堆子进程,当遇到错误或者操作失误的时候把父进程关闭了,但是子进程还在跑,不得不一个一个地杀死子进程,或者使用ps,grep,awk,kill来配合批量杀死。
之前在写 xxfpm(一个PHP-CGI的进程管理) 的时候,在Linux下使用父进程给子进程信号通知的方式来达到用户杀死父进程时,子进程也随即关闭。但是这种方法不太完美。例如,如果父进程被KILL信号杀死,完全没有机会给子进程发送信号了。
在网上搜了一下,用Linux下libc的prctl设置PR_SET_PDEATHSIG属性,似乎可以让子进程在父进程自动结束后接收到信号。这个方法似乎很完美!!!
PR_SET_PDEATHSIG (since Linux 2.1.57) Set the parent process death signal of the calling process to arg2 (either a signal value in the range 1..maxsig, or 0 to clear). This is the signal that the calling process will get when its parent dies. This value is cleared for the child of a fork(2).
测试代码:
#!/usr/bin/env python import os import ctypes import time libc = ctypes.CDLL('libc.so.6') for i in xrange(4): pid = os.fork() if pid == 0: libc.prctl(1, 15) while True: print 'Child:', i time.sleep(1) raise SystemExit print 'Wait for 10 sec...' time.sleep(10) print 'Exit'
又来看你了
你什么时候放下,什么时候就没有烦恼。