使用陷阱终止 bash 中的函数

Using trap to terminate a function in bash

我在 bash 中有一个函数,称之为 "timer",它只显示经过的秒数。目前,它在一个单独的进程中运行,完成后父进程将其杀死。

我希望函数以某种方式捕获信号并优雅地退出,但我不知道如何实现。这是现在的示例脚本:

#!/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

两件事:

  1. 不要用kill -9杀掉它。 SIGKILL 无法捕获。它不会让目标进程进行任何清理。只需执行简单的 kill 即可发送 SIGTERM 信号。

  2. 您可以在 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"