在多进程编程的时候,经常会遇到这样的情况。父进程创建了一堆子进程,当遇到错误或者操作失误的时候把父进程关闭了,但是子进程还在跑,不得不一个一个地杀死子进程,或者使用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).
测试代码:
view plaincopy to clipboardprint?
01.#!/usr/bin/env python
02.
03.import os
04.import ctypes
05.import time
06.
07.libc = ctypes.CDLL('libc.so.6')
08.
09.for i in xrange(4):
10. pid = os.fork()
11. if pid == 0:
12. libc.prctl(1, 15)
13. while True:
14. print 'Child:', i
15. time.sleep(1)
16. raise SystemExit
17.
18.print 'Wait for 10 sec...'
19.time.sleep(10)
20.print 'Exit'