[英]How to kill a python child process created with subprocess.check_output() when the parent dies?
我在 linux 机器上运行一个 python 脚本,它使用 subprocess.check_output() 创建一个子进程,如下所示:
subprocess.check_output(["ls", "-l"], stderr=subprocess.STDOUT)
问题是即使父进程死了,子进程仍在运行。 当父母去世时,有什么办法可以杀死子进程吗?
是的,您可以通过两种方法实现这一点。 他们都要求你使用Popen
而不是check_output
。 第一种是更简单的方法,使用try..finally,如下:
from contextlib import contextmanager
@contextmanager
def run_and_terminate_process(*args, **kwargs):
try:
p = subprocess.Popen(*args, **kwargs)
yield p
finally:
p.terminate() # send sigterm, or ...
p.kill() # send sigkill
def main():
with run_and_terminate_process(args) as running_proc:
# Your code here, such as running_proc.stdout.readline()
这将捕获 sigint(键盘中断)和 sigterm,但不会捕获 sigkill(如果您使用 -9 终止脚本)。
另一种方法稍微复杂一些,它使用 ctypes 的 prctl PR_SET_PDEATHSIG。 一旦父母出于任何原因(甚至是 sigkill)退出,系统就会向孩子发送信号。
import signal
import ctypes
libc = ctypes.CDLL("libc.so.6")
def set_pdeathsig(sig = signal.SIGTERM):
def callable():
return libc.prctl(1, sig)
return callable
p = subprocess.Popen(args, preexec_fn = set_pdeathsig(signal.SIGTERM))
您的问题在于使用subprocess.check_output
- 您是对的,您无法使用该接口获取子 PID。 改用 Popen:
proc = subprocess.Popen(["ls", "-l"], stdout=PIPE, stderr=PIPE)
# Here you can get the PID
global child_pid
child_pid = proc.pid
# Now we can wait for the child to complete
(output, error) = proc.communicate()
if error:
print "error:", error
print "output:", output
为了确保你在退出时杀死孩子:
import os
import signal
def kill_child():
if child_pid is None:
pass
else:
os.kill(child_pid, signal.SIGTERM)
import atexit
atexit.register(kill_child)
不知道具体细节,但最好的方法仍然是用信号捕获错误(甚至可能是所有错误)并终止那里的任何剩余进程。
import signal
import sys
import subprocess
import os
def signal_handler(signal, frame):
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
a = subprocess.check_output(["ls", "-l"], stderr=subprocess.STDOUT)
while 1:
pass # Press Ctrl-C (breaks the application and is catched by signal_handler()
这只是一个模型,您需要捕获的不仅仅是 SIGINT,但这个想法可能会让您开始,并且您仍然需要以某种方式检查生成的进程。
http://docs.python.org/2/library/os.html#os.kill http://docs.python.org/2/library/subprocess.html#subprocess.Popen.pid http://docs. python.org/2/library/subprocess.html#subprocess.Popen.kill
我建议重写一个个性化版本的check_output
原因,因为我刚刚意识到 check_output 实际上只是用于简单的调试等,因为在执行过程中你不能与它进行太多交互。
from subprocess import Popen, PIPE, STDOUT
from time import sleep, time
def checkOutput(cmd):
a = Popen('ls -l', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
print(a.pid)
start = time()
while a.poll() == None or time()-start <= 30: #30 sec grace period
sleep(0.25)
if a.poll() == None:
print('Still running, killing')
a.kill()
else:
print('exit code:',a.poll())
output = a.stdout.read()
a.stdout.close()
a.stdin.close()
return output
并用它做任何你想做的事情,也许将活动执行存储在一个临时变量中,并在退出时用信号或其他方式终止它们,以检测主循环的错误/关闭。
最后,您仍然需要在主应用程序中捕获终止以安全地杀死任何孩子,解决此问题的最佳方法是使用try & except
或signal
。
从 Python 3.2 开始,有一种非常简单的方法可以做到这一点:
from subprocess import Popen
with Popen(["sleep", "60"]) as process:
print(f"Just launched server with PID {process.pid}")
我认为这对于大多数用例来说是最好的,因为它简单且可移植,并且避免了对全局状态的任何依赖。
如果这个解决方案不够强大,那么我建议查看关于这个问题或Python的其他答案和讨论:如何在父进程死亡时杀死子进程? ,因为有很多巧妙的方法来解决这个问题,这些方法在可移植性、弹性和简单性方面提供了不同的权衡。 😊
您可以手动执行以下操作:
ps aux | grep <process name>
获取PID(第二列)和
kill -9 <PID>
-9 是强制杀掉
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.