Greg Greg - 1 year ago 102
Linux Question

Bash script that kills a child process after a given timeout

I have a bash script that launches a child process that crashes (actually, hangs) from time to time and with no apparent reason (closed source, so there isn't much I can do about it). As a result, I would like to be able to launch this process for a given amount of time, and kill it if it did not return successfully after a given amount of time.

Is there a simple and robust way to achieve that using bash?

P.S.: tell me if this question is better suited to serverfault or superuser.

Answer Source

(As seen in: BASH FAQ entry #68: "How do I run a command, and have it abort (timeout) after N seconds?")

If you don't mind downloading someting use timeout (sudo apt-get install timeout) and use it like:

timeout 10 ping

If you don't want to download something do what timeout does internally:

( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) & exec ping )

In the case that you want to do a timeout for more bash code, use the second option as such:

( cmdpid=$BASHPID; 
    (sleep 10; kill $cmdpid) \
   & while ! ping -w 1 
         echo crap; 
     done )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download