gpt4 book ai didi

linux - Bash:杀死子进程中的所有进程

转载 作者:IT王子 更新时间:2023-10-29 00:52:48 24 4
gpt4 key购买 nike

在 bash 中,我可以通过 pid 获取最后一个子进程的进程 ID ( $! )多变的。然后我可以在它完成之前终止这个子进程:

(sleep 5) & pid=$!
kill -9 $pid

这与宣传的一样有效。如果我现在在 sleep 之后使用更多命令扩展子进程, sleep命令在子进程被杀死后继续执行,即使其他命令永远不会执行。

例如,考虑下面的例子,它启动一个子进程并使用 ps 监视它的暗杀。 :

# Start subprocess and get its pid
(sleep 5; echo done) & pid=$!

# grep for subprocess
echo "grep before kill:"
ps aux | grep "$pid\|sleep 5"

# Kill the subprocess
echo
echo "Killing process $pid"
kill -9 $pid

# grep for subprocess
echo
echo "grep after kill:"
ps aux | grep "$pid\|sleep 5"

# Wait for sleep to finish
sleep 6

# grep for subprocess
echo
echo "grep after sleep is finished:"
ps aux | grep "$pid\|sleep 5"

如果我将其保存到名为 filename 的文件中然后运行它,我得到这个打印输出:

grep before kill:
username 7464 <...> bash filename
username 7466 <...> sleep 5
username 7467 <...> grep 7464\|sleep 5

Killing process 7464

grep after kill:
username 7466 <...> sleep 5
username 7469 <...> grep 7464\|sleep 5

grep after sleep is finished:
username 7472 <...> grep 7464\|sleep 5

来自 ps 的不重要信息命令替换为 <...> .它看起来像 kill已终止 filename 的整体 bash 执行, 离开时 sleep运行。

我怎样才能正确杀死整个子进程?

最佳答案

您可以在子 shell 中设置陷阱以在退出前杀死任何事件的作业:

 (trap 'kill $(jobs -p)' EXIT; sleep 5; echo done ) & pid=$!

关于linux - Bash:杀死子进程中的所有进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41508640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com