13

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

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

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

更多细节:

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

1 回答 1

21

I would atexit.register a function to terminate the process:

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

Or maybe:

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

Note that this doesn't help you if you do something nasty to cause python to die in a non-graceful way (e.g. via os._exit or if you cause a SegmentationFault or BusError)

于 2013-01-02T20:09:11.743 回答