父进程在python中崩溃时杀死子进程

时间:2013-01-02 20:04:04

标签: python process subprocess

我正在尝试编写一个python程序来测试用C编写的服务器.python程序使用subprocess模块启动已编译的服务器:

pid = subprocess.Popen(args.server_file_path).pid

这样可以正常工作,但是如果python程序由于错误而意外终止,则生成的进程将保持运行状态。我需要一种方法来确保如果python程序意外退出,服务器进程也会被终止。

更多细节:

  • 仅限Linux或OSX操作系统
  • 无法以任何方式修改服务器代码

1 个答案:

答案 0 :(得分:20)

我会atexit.register一个终止进程的函数:

import atexit
process = subprocess.Popen(args.server_file_path)
atexit.register(process.terminate)
pid = process.pid

或者也许:

import atexit
process = subprocess.Popen(args.server_file_path)
@atexit.register
def kill_process():
    try:
        process.terminate()
    except OSError:
        pass #ignore the error.  The OSError doesn't seem to be documented(?)
             #as such, it *might* be better to process.poll() and check for 
             #`None` (meaning the process is still running), but that 
             #introduces a race condition.  I'm not sure which is better,
             #hopefully someone that knows more about this than I do can 
             #comment.

pid = process.pid

请注意,如果你做了一些令人讨厌的事情导致python以不优雅的方式死亡(例如通过os._exit或者你导致SegmentationFault或{{{}},这对你没有帮助。 1}})