繁体   English   中英

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

[英]Killing child process when parent crashes in python

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

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

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

更多细节:

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

我会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或者如果导致SegmentationFaultBusError ),这对您没有帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM