Bash: wait with timeout

前端 未结 6 1334
再見小時候
再見小時候 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:28

    Here's a simplified version of Aaron Digulla's answer, which uses the kill -0 trick that Aaron Digulla leaves in a comment:

    app &
    pidApp=$!
    ( sleep 60 ; echo 'timeout'; kill $pidApp ) &
    killerPid=$!
    
    wait $pidApp
    kill -0 $killerPid && kill $killerPid
    

    In my case, I wanted to be both set -e -x safe and return the status code, so I used:

    set -e -x
    app &
    pidApp=$!
    ( sleep 45 ; echo 'timeout'; kill $pidApp ) &
    killerPid=$!
    
    wait $pidApp
    status=$?
    (kill -0 $killerPid && kill $killerPid) || true
    
    exit $status
    

    An exit status of 143 indicates SIGTERM, almost certainly from our timeout.

提交回复
热议问题