我在 bash 中有一个函数,称之为“计时器”,它只显示经过的秒数。目前,它在一个单独的进程中运行,父进程在完成后将其杀死。
我希望该函数能够以某种方式捕获信号并优雅地退出,但我不知道如何实现。这是现在的示例脚本:
#!/bin/bash
function timer () {
t0=$(date +%s)
while true ; do
t=$(date +%s)
echo -en "\r$(($t - $t0))"
done
}
timer &
pid=$!
echo $pid
sleep 5 # do something while timer runs
echo "done"
kill -9 $pid
最佳答案
有两件事:
不要使用
kill -9
来终止它。SIGKILL
是无法捕获的。它不会让目标进程进行任何清理。只需执行简单的kill
即可发送SIGTERM
信号。您可以在
SIGTERM
上捕获。您还可以捕获SIGINT
来捕获 Ctrl-C。或者最好,捕获EXIT
来进行清理,无论脚本如何被终止。
function timer () {
trap 'echo -e "\ntimer stopped"' EXIT
t0=$(date +%s)
while true ; do
t=$(date +%s)
echo -en "\r$(($t - $t0))"
done
}
timer &
pid=$!
echo "$pid"
sleep 5 # do something while timer runs
echo "done"
kill "$pid"
关于bash - 在 bash 中使用 trap 终止函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47772128/