后台作业失败时停止linux bash脚本

时间:2017-07-20 13:12:46

标签: bash error-handling background-process

当后台作业失败时(通过任何信号SEGV,ABRT,KILL,INT ...),当作业在后台在linux bash脚本中时,如何注意。

set -e
foo &
foo_pid=$!
# Do tasks that requires that foo is running
wait $foo_pid

不起作用。

2 个答案:

答案 0 :(得分:1)

这可以帮助

set -e
foo &
foo_pid=$!

# If this script is killed, kill the `cp'.
trap "kill $foo_pid 2> /dev/null" EXIT

while kill -0 $foo_pid 2> /dev/null; do
    # Do smth
    ...
    sleep 1
done

答案 1 :(得分:0)

尝试捕获信号并更新为包含时间和日期的文件。

set -e
act() { 
  echo "Caught signal!" > /tmp/file.txt
  echo `date` >> /tmp/file.txt
  exit
}

trap act SIGINT SIGTERM SIGKILL

foo &
foo_pid=$!
# Do tasks that requires that foo is running
wait $foo_pid