【问题标题】:How to keep running a program during a time period?如何在一段时间内保持运行程序?
【发布时间】:2014-09-19 06:32:42
【问题描述】:

我想重复运行一个程序最多 5 秒。

我知道timeout 在指定的时间内执行命令,例如:

timeout 5 ./a.out

但我想继续执行程序直到 5 秒过去,这样我才能知道如何 它被执行了很多次。

我想我需要这样的东西:

timeout 5 `while true; do ./a.out; done`

但这不起作用。我已经尝试创建一个计算的 shell 脚本 每次循环迭代的经过时间并从开始时间中减去它, 但那是低效的。

任何帮助将不胜感激。

【问题讨论】:

  • 你试过timeout 5 bash -c "while true; do ./a.out; done"
  • 如果要使用timeout,命令为timeout 5s ./a.out
  • 是的,我发现 bash -c "" 会这样做!感谢您的提示:)

标签: linux bash shell timeout


【解决方案1】:

如果你想使用超时:

timeout 5s ./a.out

您可以编写一个简短的脚本并轻松设置end timedate -d "date string" +%s 以获得以秒为单位的未来时间。然后将current timeend 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 2017-01-07
    • 1970-01-01
    • 2011-11-13
    • 2018-12-18
    • 1970-01-01
    相关资源
    最近更新 更多