【问题标题】:bash - close script by error or by timeout [duplicate]bash - 错误或超时关闭脚本[重复]
【发布时间】:2020-08-24 03:43:24
【问题描述】:

在 stackoverflow 上有很多解决方案 - 如何通过超时关闭脚本或在出现错误时关闭脚本。 但是如何将这两种方法结合在一起呢? 如果在执行脚本期间出现错误 - 关闭脚本。 如果超时 - 关闭脚本。

我有以下代码:

#!/usr/bin/env bash
set -e
finish_time=$1
echo "finish_time=" ${finish_time}
(./execute_something.sh) & pid=$!
sleep ${finish_time}
kill $pid

但是如果在执行过程中出现错误 - 脚本仍然在等待,超时就会结束。

【问题讨论】:

  • 所以wait 在孩子身上,有一个超时。如果您等待的时间较短,那么finish_time 并且孩子的退出状态为零,然后等到finish_time。如果子状态不为零,则退出并出错。如果您waited 时间过长并且超时,请执行其他操作。
  • 如果您使用的是现代 Linux(使用 GNU coreutils),您将有一个 timeout 命令为您完成所有这些工作。运行 timeout "$finish_time" ./execute_something.sh 就可以了。

标签: linux bash shell


【解决方案1】:

首先,我不会使用set -e

你会明确地等待你想要的工作; wait 的退出状态将是作业本身的退出状态。

echo "finish_time = $1"

./execute_something.sh & pid=$!
sleep "$1" & sleep_pid=$!

wait -n  # Waits for either the sleep or the script to finish
rv=$?

if kill -0 $pid; then
    # Script still running, kill it
    # and exit 
    kill -s ALRM $pid
    wait $pid  # exit status will indicte it was killed by SIGALRM
    exit
else
    # Script exited before sleep
    kill $sleep_pid
    exit $rv
fi

这里有一个轻微的竞争条件;它是这样的:

  1. wait -nsleep退出后返回,表示脚本会自行退出
  2. 脚本在我们检查它是否仍在运行之前退出
  3. 因此,我们假设它实际上是在睡眠之前退出的。

但这只是意味着我们将创建一个运行略微超过阈值的脚本,以按时完成。这可能不是您关心的区别。

理想情况下,wait 会设置一些 shell 参数来指示哪个进程导致它返回。

【讨论】:

    猜你喜欢
    • 2013-01-24
    • 2013-09-15
    • 2010-11-05
    • 2023-01-15
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    相关资源
    最近更新 更多