SteveHNH
SteveHNH

Reputation: 119

Kill a process generated by for loop after certain time

I have some code that tends to hang randomly inside it's 'for loop'. I'm looking for a solution that will automatically kill the ssh session's PID if it exists for 5 seconds. I'm killing the hung processes right now manually, but I want to put this in cron so automatic PID killing would be awesome.

for host in `cat $WORKDIR/linux_hosts.txt $WORKDIR/aix_hosts.txt`
do
    ssh -o LogLevel=QUIET -o ConnectTimeout=2 -t $host "cat /etc/passwd" >> $FILEDIR/$host
done

Thanks for the help!

Upvotes: 0

Views: 981

Answers (3)

chepner
chepner

Reputation: 531798

Run all the ssh processes in the background, then wait 5 seconds. Once sleep returns, use jobs -p to get the process IDs of any background jobs still running, and kill them.

cat "$WORKDIR"/{linux_hosts.txt,aix_hosts.txt} | while read host; do
    ssh -o LogLevel=QUIET -o ConnectTimeout=2 -t "$host" "cat /etc/passwd" >> "$FILEDIR/$host" &
done
sleep 5
kill $(jobs -p) 2>/dev/null

Upvotes: 2

Joao Morais
Joao Morais

Reputation: 1935

This will find and kill all ssh process older than 5 minutes.

cd /proc
kill $(find $(pidof ssh) -maxdepth 0 -mmin +5)

Upvotes: 0

dave4420
dave4420

Reputation: 47062

Use timeout:

for host in `cat $WORKDIR/linux_hosts.txt $WORKDIR/aix_hosts.txt`
do
    timeout 5s ssh -o LogLevel=QUIET -o ConnectTimeout=2 -t $host \
                   "cat /etc/passwd" >> $FILEDIR/$host
done

Upvotes: 0

Related Questions