subprocess.Popen("bash file.sh"):如何终止 Bash 脚本及其所有后台作业

subprocess.Popen("bash file.sh"): how to kill the Bash script and all its background jobs

我有一个 bash 脚本,它 运行 在后台运行多个进程。如果我 运行 bash 终端中的脚本,我可以使用 Ctrl-C 关闭它们。

当我 运行 使用 subprocess.Popen 的脚本时,我无法关闭它们。我可以修改这两个脚本来让它工作。

我只想在 bash 中打开多个进程,并在我想关闭时向它们发送终止信号。我可以尝试不同的方法。

Bash 脚本

#!/bin/bash

ping -i 5 google.com &
ping -i 4 example.com &

wait

示例 Python 脚本:

import subprocess
import signal

command = "bash script.sh"
p = subprocess.Popen(command.split())

print("Started")
try:
  p.wait(5) # waits 5 seconds
except:
  print("Kill")

  # These just terminates script.py but pings still working
  #p.kill()
  #p.terminate()
  p.send_signal(signal.SIGINT)

p.wait() # does not wait
print("Ended")

您必须捕获 SIGTERM 并终止子进程。在 bash 文件中的 wait 之前添加以下代码。您还需要发送 SIGTERM 或使用 Popen 对象的终止函数。

function trap_sigterm() {
    pkill -SIGINT -P $$  # Kill child processes of $$ (this)
    exit
}

trap trap_sigterm SIGTERM