Killing child process when parent crashes in python(当父母在python中崩溃时杀死子进程)
问题描述
我正在尝试编写一个 python 程序来测试用 C 编写的服务器.python 程序使用 subprocess
模块启动编译的服务器:
I am trying to write a python program to test a server written in C. The python program launches the compiled server using the subprocess
module:
pid = subprocess.Popen(args.server_file_path).pid
这工作正常,但是如果 python 程序由于错误而意外终止,则生成的进程将继续运行.我需要一种方法来确保如果 python 程序意外退出,服务器进程也会被终止.
This works fine, however if the python program terminates unexpectedly due to an error, the spawned process is left running. I need a way to ensure that if the python program exits unexpectedly, the server process is killed as well.
更多细节:
- 仅限 Linux 或 OSX 操作系统
- 不能以任何方式修改服务器代码
推荐答案
我会atexit.register
终止进程的函数:
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
或许:
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
或 BusError
)
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
)
这篇关于当父母在python中崩溃时杀死子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当父母在python中崩溃时杀死子进程
基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01