python守护进程中的子进程杀死

2022-01-18 00:00:00 python subprocess daemon

问题描述

我在 python 中有运行外部程序的 damon:

I have damon in python which runs external program:

subprocess.call(["java", "-jar", "start.jar"])

当我杀死守护进程时,子进程(java)仍在运行

when I kill daemon, the child process (java) is still running

我怎样才能让子进程也被杀死?

how can I make so that child process is also killed ?


解决方案

使用 subprocess.Popen() 而不是 subprocess.call().例如:

Use subprocess.Popen() instead of subprocess.call(). For example:

import subprocess
my_process = subprocess.Popen(['ls', '-l'])

终止孩子:

my_process.kill()

要捕获终止信号,您可以这样:

To capture the kill signal, you could so something like this:

import signal
import sys
def signal_handler(signal, frame):
    sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)

相关文章