在多進程編程的時候,經常會遇到這樣的情況。父進程創建了一堆子進程,當遇到錯誤或者操作失誤的時候把父進程關閉了,但是子進程還在跑,不得不一個一個地殺死子進程,或者使用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'