我试图编写一个python程序来测试用C编写的服务器。python程序使用subprocess模块启动编译后的服务器:
pid = subprocess.Popen(args.server_file_path).pid但是,如果python程序由于错误而意外终止,则生成的进程将继续运行。我需要一种方法来确保如果python程序意外退出,服务器进程也会被杀死。
更多细节:
发布于 2013-01-02 20:09:11
我将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或如果您导致SegmentationFault或BusError),这对您没有任何帮助。
https://stackoverflow.com/questions/14128410
复制相似问题