Bash: wait with timeout

前端 未结 6 1333
再見小時候
再見小時候 2020-12-02 16:39

In a Bash script, I would like to do something like:

app1 &
pidApp1=$!
app2 &
pidApp2=$1

timeout 60 wait $pidApp1 $pidApp2
kill -9 $pidApp1 $pidApp2         


        
6条回答
  •  無奈伤痛
    2020-12-02 17:31

    I wrote a bash function that will wait until PIDs finished or until timeout, that return non zero if timeout exceeded and print all the PIDs not finisheds.

    function wait_timeout {
      local limit=${@:1:1}
      local pids=${@:2}
      local count=0
      while true
      do
        local have_to_wait=false
        for pid in ${pids}; do
          if kill -0 ${pid} &>/dev/null; then
            have_to_wait=true
          else
            pids=`echo ${pids} | sed -e "s/${pid}//g"`
          fi
        done
        if ${have_to_wait} && (( $count < $limit )); then
          count=$(( count + 1 ))
          sleep 1
        else
          echo ${pids}
          return 1
        fi
      done   
      return 0
    }
    

    To use this is just wait_timeout $timeout $PID1 $PID2 ...

提交回复
热议问题