Skip to content

Instantly share code, notes, and snippets.

@zouppen
Created April 19, 2012 13:18
Show Gist options
  • Save zouppen/2420935 to your computer and use it in GitHub Desktop.
Save zouppen/2420935 to your computer and use it in GitHub Desktop.
Runs a process for a given time
#!/bin/bash -eu
#
# Runs a process for given time (timeout format is same as in
# sleep(1)) and terminates it with SIGTERM after timeout occurs.
#
# Author: Joel Lehtonen <joel.lehtonen@iki.fi>
# Keeps some parameters and alters positional parameters
TIMEOUT=$1
PROG=$2
shift 2
# Somewhat dangerous trick begins: It forks subshell which kills the
# parent. The dangerous part is that if the parent dies before timeout
# and a new process has reused the PID. In that case it kills an
# outsider. I'm sorry.
(
sleep "$TIMEOUT"
# Kill -s 0 doesn't kill but returns failure if PID is dead. That
# terminates this script because we have -e option.
kill -s 0 $$ 2>/dev/null
echo "Timeout of $TIMEOUT reached"
kill $$
) &
# Replaces current shell with the desired process. To allow running of
# programs requiring tty access, we have to do it this way.
exec "$PROG" "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment