我如何限制bash脚本的运行时间

编程入门 行业动态 更新时间:2024-10-10 07:27:33
本文介绍了我如何限制bash脚本的运行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有我在Cygwin下在Windows上运行的长时间运行的bash脚本。

I have a long running BASH script that I am running under CYGWIN on Windows.

我想限制脚本运行30秒,并且如果它超过该极限自动终止。理想情况下,我希望能够做到这一点的任何命令。

I would like to limit the script to run for 30 seconds, and automatically terminate if it exceeds this limit. Ideally, I'd like to be able to do this to any command.

例如:

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

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

在Cygwin的ulimit命令似乎不工作。

Under cygwin the ulimit command doesn't seem to work.

我愿意接受任何想法。

推荐答案

查看 www.pixelbeat/scripts /超时脚本的功能已经被集成到新的coreutils:

See the www.pixelbeat/scripts/timeout script the functionality of which has been integrated into newer coreutils:

#!/bin/sh # Execute a command with a timeout # License: LGPLv2 # Author: # www.pixelbeat/ # 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> # Make more portable by using the 'CHLD' # signal spec rather than 17. # V1.3, Oct 29 2009, Ján Sáreník <jasan@x31> # 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> # 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

更多推荐

我如何限制bash脚本的运行时间

本文发布于:2023-11-23 13:23:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621596.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   时间   bash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!