如何在一段时间内继续运行程序?
问题描述:
我想重复运行程序最多5秒钟。如何在一段时间内继续运行程序?
我知道timeout
指定的时间量,例如,执行命令:
timeout 5 ./a.out
但我要继续执行程序,直到5秒过去了,所以我可以告诉它如何 多次获得执行。
我想,我需要这样的:
timeout 5 `while true; do ./a.out; done`
,但是这是行不通的。我已经尝试创建一个shell脚本,用于计算每个循环迭代耗用的时间,并从开始时间 中减去它,但效率不高。
任何帮助,将不胜感激。
答
如果你想使用的超时:
timeout 5s ./a.out
您可以编写一个简短的脚本,轻松地设置与date -d "date string" +%s
的end time
获得以秒为将来的时间。然后,只需比较current time
至end time
并打破true
。这允许您在执行期间捕获更多数据。例如,以下代码将来会设置结束时间5 seconds
,然后循环直到current time
等于end
。
#!/bin/bash
end=$(date -d "+ 5 seconds" +%s) # set end time with "+ 5 seconds"
declare -i count=0
while [ $(date +%s) -lt $end ]; do # compare current time to end until true
((count++))
printf "working... %s\n" "$count" # do stuff
sleep .5
done
输出:
$ bash timeexec.sh
working... 1
working... 2
working... 3
working... 4
working... 5
working... 6
working... 7
working... 8
working... 9
在你的情况,你会做这样的事情
./a.out & # start your application in background
apid=$(pidof a.out) # save PID of a.out
while [ $(date +%s) -lt $end ]; do
# do stuff, count, etc.
sleep .5 # something to prevent continual looping
done
kill $apid # kill process after time test true
你尝试'超时5的bash -c“,而真实;做./a。 out; done“' – 2014-09-19 06:39:35
如果你想使用'timeout',命令是'timeout 5s。/ a.out' – 2014-09-19 07:35:05
是的,我发现bash -c”“会这么做!谢谢你的提示 :) – 2014-09-19 14:48:16