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.
If you don’t mind downloading something, use
sudo apt-get install timeout) and use it like: (most Systems have it already installed otherwise use
sudo apt-get install coreutils)
timeout 10 ping www.goooooogle.com
If you don’t want to download something, do what timeout does internally:
( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) & exec ping www.goooooogle.com )
In case that you want to do a timeout for longer bash code, use the second option as such:
( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) \ & while ! ping -w 1 www.goooooogle.com do echo crap; done )
# Spawn a child process: (dosmth) & pid=$! # in the background, sleep for 10 secs then kill that process (sleep 10 && kill -9 $pid) &
or to get the exit codes as well:
# Spawn a child process: (dosmth) & pid=$! # in the background, sleep for 10 secs then kill that process (sleep 10 && kill -9 $pid) & waiter=$! # wait on our worker process and return the exitcode exitcode=$(wait $pid && echo $?) # kill the waiter subshell, if it still runs kill -9 $waiter 2>/dev/null # 0 if we killed the waiter, cause that means the process finished before the waiter finished_gracefully=$?