如何限制 BASH 脚本的运行时间
我有一个长时间运行的 BASH 脚本,正在 Windows 上的 CYGWIN 下运行。
我想限制脚本运行30秒,如果超过这个限制就自动终止。 理想情况下,我希望能够对任何命令执行此操作。
例如:
$ limittime -t 30 'myscript.sh'
或
$ limittime -t 30 'grep func *.c'
在 cygwin 下,ulimit 命令似乎不起作用。
I have a long running BASH script that I am running under CYGWIN on Windows.
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.
For example:
$ limittime -t 30 'myscript.sh'
or
$ limittime -t 30 'grep func *.c'
Under cygwin the ulimit command doesn't seem to work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请参阅 http://www.pixelbeat.org/scripts/timeout 脚本,其功能具有已集成到较新的 coreutils 中:
See the http://www.pixelbeat.org/scripts/timeout script the functionality of which has been integrated into newer coreutils:
以下脚本演示了如何使用后台任务来执行此操作。 第一部分在 10 秒限制后终止 60 秒的进程。 第二个尝试终止已经退出的进程。 请记住,如果您将超时设置得非常高,进程 ID 可能会翻转,您将杀死错误的进程,但这更多的是一个理论问题 - 超时必须非常很大,您将必须启动很多进程。
这是我的 Cygwin 盒子上的输出:
如果您只想等到进程完成,则需要输入一个循环并进行检查。 这稍微不太准确,因为
sleep 1
和其他命令实际上需要超过一秒(但不会多得多)。 使用此脚本替换上面的第二部分(“echo $proc
”和“date
”命令用于调试,我不希望将它们放在最终的解决方案)。它基本上循环,每秒检查进程是否仍在运行。 如果不是,它会以特殊值退出循环,以免尝试杀死子进程。 否则它会超时并杀死孩子。
的输出:
以下是
sleep 3
和sleep 60
The following script shows how to do this using background tasks. The first section kills a 60-second process after the 10-second limit. The second attempts to kill a process that's already exited. Keep in mind that, if you set your timeout really high, the process IDs may roll over and you'll kill the wrong process but this is more of a theoretical issue - the timeout would have to be very large and you would have to be starting a lot of processes.
Here's the output on my Cygwin box:
If you want to only wait until the process has finished, you need to enter a loop and check. This is slightly less accurate since
sleep 1
and the other commands will actually take more than one second (but not much more). Use this script to replace the second section above (the "echo $proc
" and "date
" commands are for debugging, I wouldn't expect to have them in the final solution).It basically loops, checking if the process is still running every second. If not, it exits the loop with a special value to not try and kill the child. Otherwise it times out and does kill the child.
Here's the output for a
sleep 3
:and a
sleep 60
:查看此链接。 这个想法只是,您可以将
myscript.sh
作为脚本的子进程运行并记录其 PID,然后在运行时间过长时将其终止。Check out this link. The idea is just that you would run
myscript.sh
as a subprocess of your script and record its PID, then kill it if it runs too long.以下是 coreutils 下“超时”的所有选项:
Below are all the options for "timeout" under coreutils:
您可以将命令作为后台作业运行(即使用“&”),使用 bash 变量作为“最后一个命令运行的 pid”,休眠所需的时间,然后运行
kill
那个pid。You could run the command as a background job (i.e. with "&"), use the bash variable for "pid of last command run," sleep for the requisite amount of time, then run
kill
with that pid.