加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何限制BASH脚本的运行时间

发布时间:2020-12-15 19:08:58 所属栏目:安全 来源:网络整理
导读:我有一个长时间运行的BASH脚本,我在Windows上运行CYGWIN。 我想限制脚本运行30秒,如果超过此限制,则自动终止。理想情况下,我希望能够对任何命令执行此操作。 例如: sh-3.2$ limittime -t 30 'myscript.sh' 要么 sh-3.2$ limittime -t 30 'grep func *.c
我有一个长时间运行的BASH脚本,我在Windows上运行CYGWIN。

我想限制脚本运行30秒,如果超过此限制,则自动终止。理想情况下,我希望能够对任何命令执行此操作。

例如:

sh-3.2$ limittime -t 30 'myscript.sh'

要么

sh-3.2$ limittime -t 30 'grep func *.c'

在cygwin下,ulimit命令似乎不起作用。

我愿意接受任何想法。

请参阅 http://www.pixelbeat.org/scripts/timeout脚本,其功能已集成到较新的coreutils中:
#!/bin/sh

# Execute a command with a timeout

# License: LGPLv2
# Author:
#    http://www.pixelbeat.org/
# Notes:
#    Note there is a timeout command packaged with coreutils since v7.0
#    If the timeout occurs the exit status is 124.
#    There is an asynchronous (and buggy) equivalent of this
#    script packaged with bash (under /usr/share/doc/ in my distro),#    which I only noticed after writing this.
#    I noticed later again that there is a C equivalent of this packaged
#    with satan by Wietse Venema,and copied to forensics by Dan Farmer.
# Changes:
#    V1.0,Nov  3 2006,Initial release
#    V1.1,Nov 20 2007,Brad Greenlee <brad@footle.org>
#                       Make more portable by using the 'CHLD'
#                       signal spec rather than 17.
#    V1.3,Oct 29 2009,Ján Sáreník <jasan@x31.com>
#                       Even though this runs under dash,ksh etc.
#                       it doesn't actually timeout. So enforce bash for now.
#                       Also change exit on timeout from 128 to 124
#                       to match coreutils.
#    V2.0,Oct 30 2009,Ján Sáreník <jasan@x31.com>
#                       Rewritten to cover compatibility with other
#                       Bourne shell implementations (pdksh,dash)

if [ "$#" -lt "2" ]; then
    echo "Usage:   `basename $0` timeout_in_seconds command" >&2
    echo "Example: `basename $0` 2 sleep 3 || echo timeout" >&2
    exit 1
fi

cleanup()
{
    trap - ALRM               #reset handler to default
    kill -ALRM $a 2>/dev/null #stop timer subshell if running
    kill $! 2>/dev/null &&    #kill last job
      exit 124                #exit with 124 if it was running
}

watchit()
{
    trap "cleanup" ALRM
    sleep $1& wait
    kill -ALRM $$
}

watchit $1& a=$!         #start the timeout
shift                    #first param was timeout for sleep
trap "cleanup" ALRM INT  #cleanup after timeout
"$@"& wait $!; RET=$?    #start the job wait for it and save its return value
kill -ALRM $a            #send ALRM signal to watchit
wait $a                  #wait for watchit to finish cleanup
exit $RET                #return the value

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读