如何杀死 Bash 中的子进程?

How to kill child processes in Bash?

我正尝试在 linux 中尝试使用 openssl speed

刻录 cpu

这是我来自 netflix simian army 的代码

#!/bin/bash
# Script for BurnCpu Chaos Monkey

cat << EOF > /tmp/infiniteburn.sh
#!/bin/bash
while true;
   do openssl speed;
done
EOF

# 32 parallel 100% CPU tasks should hit even the biggest EC2 instances
for i in {1..32}
do
  nohup /bin/bash /tmp/infiniteburn.sh &
done

所以这是 Netflix simian army code 用于烧录 cpu,这可以正常执行,但问题是我无法杀死所有 32 个进程,我尝试了所有方法

pkill -f pid/process name
killall -9 pid/process name
etc.,

我终止进程的唯一成功方法是通过用户终止它

pkill -u username

如何在不使用用户名的情况下终止这些进程?

非常感谢任何帮助

终止进程不会自动终止其子进程。终止 bash 脚本不会终止 openssl speed 进程。

您可以通过 kill 呼叫来广撒网,这正是您在 pkill -u 中所做的。或者您可以在脚本中使用 trap 并添加错误处理程序。

cleanup() {
    # kill children
}

trap cleanup EXIT

终于,我找到了自己问题的解决方案,

kill -- -$(ps -o pgid= $PID | grep -o [0-9]*)

其中 PID 是任何一个进程的进程 ID 运行,这工作正常,但我愿意听到任何其他可用的选项

来源:http://fibrevillage.com/sysadmin/237-ways-to-kill-parent-and-child-processes-in-one-command

我有一个类似的问题和解决方案,我需要在一段时间后终止 NodeJS 服务器。

为此,我启用了 Job control, and killed async processes by group id with jobs:

set -m
./node_modules/.bin/node src/index.js &
sleep 2

kill -- -$(jobs -p)