我想重复运行一个程序,最多5秒。
我知道timeout
在指定的时间内执行命令,例如:
timeout 5 ./a.out
但是我想继续执行这个程序,直到5秒过去,这样我就可以知道
多次被处决。
我想我需要这样的东西:
timeout 5 `while true; do ./a.out; done`
但这不管用。我已经尝试创建一个shell脚本来计算
每次循环迭代的经过时间,并从开始时间中减去,
但这是低效的。
任何帮助都将不胜感激。
最佳答案
如果要使用超时:
timeout 5s ./a.out
您可以编写一个简短的脚本,并使用
end time
轻松设置date -d "date string" +%s
,以获得以秒为单位的未来时间。然后比较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
关于linux - 如何在一段时间内继续运行程序?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25927710/