Checking and killing hanged background processes in a bash script

2.4k views Asked by At

Say I have this pseudocode in bash

#!/bin/bash

things    
for i in {1..3}
do
    nohup someScript[i] &

done
wait

for i in {4..6}
do
    nohup someScript[i] &

done
wait
otherThings

and say this someScript[i] sometimes end up hanging.

Is there a way I can take the process IDs (with $!) and check periodically if the process is taking more than a specified amount of time after which I want to kill the hanged processes with kill -9 ?

2

There are 2 answers

4
Marco Pietrosanto On BEST ANSWER

Unfortunately the answer from @Eugeniu did not work for me, timeout gave an error.

However I found useful doing this routine, I'll post it here so anyone can take advantage of it if in my same problem.

Create another script which goes like this

#!/bin/bash
#monitor.sh

pid=$1

counter=10
while ps -p $pid > /dev/null
do
    if [[ $counter -eq 0 ]] ; then
            kill -9 $pid
    #if it's still there then kill it
    fi
    counter=$((counter-1))
    sleep 1
done

then in the main work you just put

things    
for i in {1..3}
do
    nohup someScript[i] &
    ./monitor.sh $! &
done
wait

In this way for any of your someScript you will have a parallel process that checks if it's still there every chosen interval (until maximum time decided by the counter) and that actually quit itself if the associated process dies (or gets killed)

6
Eugeniu Rosca On

One possible approach:

#!/bin/bash

# things
mypids=()
for i in {1..3}; do
    # launch the script with timeout (3600s)
    timeout 3600 nohup someScript[i] &
    mypids[i]=$! # store the PID
done

wait "${mypids[@]}"