【问题标题】:Killing child process when parent crashes in python当父母在python中崩溃时杀死子进程
【发布时间】:2012-12-17 04:41:39
【问题描述】:

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

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

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

更多细节:

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

【问题讨论】:

  • "由于错误" -- 什么样的错误?
  • 网络错误、键盘中断等
  • supervisor 是一个用 Python 编写的开源进程管理守护进程。如果有时间,源代码可能值得一看。

标签: python process subprocess


【解决方案1】:

我会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

【讨论】:

  • @ire_and_curses -- 感谢您添加链接。不胜感激。
  • “讨厌的案子”是最有趣的)
  • 我在stackoverflow.com/questions/25542110/… 中为“讨厌的情况”提供了一个选项,但在这里没有帮助(它需要访问客户端源代码)。
猜你喜欢
  • 2014-09-16
  • 2013-09-19
  • 2014-06-19
  • 2015-03-17
  • 2016-11-09
  • 1970-01-01
  • 2016-06-05
  • 1970-01-01
相关资源
最近更新 更多