如何反复启动和杀死永无止境的bash进程

时间:2018-02-01 01:18:22

标签: bash shell sh

如何重复启动并终止需要很长时间的bash脚本。我有一个无限期运行的analyze_realtime.sh,但我只想在X秒爆发时运行它(现在只说15秒)。

while true; do analyze_realtime.sh; sleep 15; done

这个问题是analyze_realtime.sh永远不会完成,所以这个逻辑不起作用。有没有办法在15秒后杀死进程,然后重新启动它?

我在考虑使用analyze_realtime.sh&pskill可能会有效。还有什么更简单的吗?

3 个答案:

答案 0 :(得分:3)

试试这个

while true; do
    analyze_realtime.sh & # put script execution in background
    sleep 15
    kill %1
done

说明

%1是指在后台运行的最新流程

答案 1 :(得分:3)

<div id="pasta-results">Please wait, loading...</div>

<script type="text-javascript">
    function loadPasta() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("pasta-results").innerHTML = this.responseText;
        }
      };
      xhttp.open("GET", "http://website-host/pasta", true);
      xhttp.send();
    }

    function loadCooking() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          loadPasta();
        }
      };
      xhttp.open("GET", "http://website-host/cooking", true);
      xhttp.send();
    }

    loadCooking();
<script>

如果 while true; do analyze_realtime.sh & jobpid=$! # This gets the pid of the bg job sleep 15 kill $jobpid if ps -p $jobpid &>/dev/null; then echo "$jobpid didn't get killed. Moving on..." fi done 无法正常工作,您可以在if-statement下执行更多操作,并发送其他信号。

答案 2 :(得分:1)

您可以使用timeout中的coreutils实用程序:

while true; do
    timeout 15 analyze_realtime.sh
done

(灵感来自this answer

相关问题