Last active
November 25, 2022 14:16
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
#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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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