异步监视和中断 shell 脚本

问题描述

我有一个调用一些数据处理函数的 shell 脚本。这些功能可以长时间运行。 我想更新脚本以中断正在运行的过程,以防从外部来源看到某个“状态”。否则程序应该正常完成。

我编写了一个 monitor_status 函数并异步调用。如果找到状态,该函数会向主进程发送一个终止命令。我有以下问题

  1. 如果从 monitor_status 函数调用 kill -15 $,则清理函数将被调用两次。我怎样才能防止这种情况发生?
  2. 如果主进程正常完成,我应该如何终止monitor_status函数

还请建议是否有更好的方法来处理这种情况以及我可以对脚本进行的任何其他改进

bash 脚本如下所示:

#!/bin/bash

function cleanup() {
  echo "cleanup invoked"
  if [[ -n "${child}" ]]; then
    echo "Stopping the child"
    kill "${child}" >/dev/null 2>&1 || true
  fi
  echo "cleanup done"
}

function main() { 
    echo "Starting main process"
    # do long running data processing
    echo "Exiting Main"
}

function monitor_status() { 
    echo "checking status"
    $Status = get_status
    if [[ $Status = "Terminate" ]]; then
        echo "Alert Alert!!!"
        kill -15 $$
    fi
    sleep 5
    done
}

monitor_status &
main &
trap cleanup SIGTERM EXIT
child=$!
wait "${child}"

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)