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

cha*_*e55 12 python subprocess process

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

pid = subprocess.Popen(args.server_file_path).pid
Run Code Online (Sandbox Code Playgroud)

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

更多细节:

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

mgi*_*son 20

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

import atexit
process = subprocess.Popen(args.server_file_path)
atexit.register(process.terminate)
pid = process.pid
Run Code Online (Sandbox Code Playgroud)

或者可能:

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
Run Code Online (Sandbox Code Playgroud)

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

  • "令人讨厌的案例"是最有趣的一个) (3认同)