gpt4 book ai didi

linux - ctrl+c 杀死带有子进程的 bash 脚本

转载 作者:太空狗 更新时间:2023-10-29 12:02:07 24 4
gpt4 key购买 nike

我有一个脚本,其内部结构归结为:

trap "exit" SIGINT SIGTERM
while :
do
mplayer sound.mp3
sleep 3
done

(是的,它比上面的更有意义,但这与问题无关)。多个脚本实例可能同时运行。

有时我想 ^C 脚本...但那不会成功。据我了解,当 ^C 杀死 mplayer 时,它继续 sleep,而当 ^C 杀死 sleep 时,它继续 mplayer ,我从来没有碰巧在两者之间捕获它。据我了解,trap 根本行不通。

如何终止脚本?

最佳答案

您可以获得mplayer 的PID,并在捕获时向mplayer 的PID 发送kill 信号。

function clean_up {

# Perform program exit housekeeping
KILL $MPLAYER_PID
exit
}

trap clean_up SIGHUP SIGINT SIGTERM
mplayer sound.mp3 &
MPLAYER_PID=$!
wait $MPLAYER_PID

关于linux - ctrl+c 杀死带有子进程的 bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31314887/

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