Skip to content

Instantly share code, notes, and snippets.

@pablochacin
Last active November 25, 2022 14:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablochacin/6999868 to your computer and use it in GitHub Desktop.
Save pablochacin/6999868 to your computer and use it in GitHub Desktop.
A bash function to execute another function and kill it if it takes longer than a given timeout. Much like the timeout command, but works with functions.
#
#executes another function as a subprocess and kills it if takes longer than a given timeout
# $1 timeout
# $2 name of function
# $@ argument list for function
function watchdog(){
local T=$1
local F=$2
shift;shift
$F $@ &
PID=$!
#check every second. If finished, return
for S in $(seq 1 $T)
do
sleep 1
if ! ps -p $PID >> /dev/null
then
return
fi
done
kill $PID 2> /dev/null
}
#!/bin/bash
source watchdog.sh
#
# This script executes the delayed_echo using the watchdog function.
# $1 timeout passed to watchdog
#
#
# Waits for a given time and writes a message to stdout
#
# $1 delay
# $2 message
function delayed_echo(){
sleep $1
echo "$2"
}
watchdog $1 delayed_echo $2 $3
Execute with a timeout longer than the delay
>./watchdog_test.sh 10 5 "Echoed"
Echoed
Execute with a timeout shorter than delay
>./watchdog_test.sh 3 5 "Echoed"
>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment