Skip to content

Instantly share code, notes, and snippets.

@etam
Last active February 23, 2017 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save etam/0bfa78f4d37168b0c0d70939cc8f51cb to your computer and use it in GitHub Desktop.
Save etam/0bfa78f4d37168b0c0d70939cc8f51cb to your computer and use it in GitHub Desktop.
#!/bin/bash
numeric_or_default() {
local -i val="$1"
local -i default="$2"
if [[ "$1" == "$val" ]]; then
echo "$val"
else
echo "$default"
fi
}
declare -i fake_daemon_die_timeout_secs
fake_daemon_die_timeout_secs="$(numeric_or_default "$fake_daemon_die_timeout_secs" "0")"
declare -i fake_daemon_exit_code
fake_daemon_exit_code="$(numeric_or_default "$fake_daemon_exit_code" "0")"
fake_daemon_dying="${fake_daemon_dying:-false}"
loop=true
declare -i run_time
run_time=0
got_signal() {
echo "got signal"
if [[ "$fake_daemon_dying" == "false" ]]; then
fake_daemon_dying=true
else
loop=false
fi
}
trap 'got_signal' INT TERM
while [[ "$loop" == "true" && ! ( "$fake_daemon_dying" == "true" && "$fake_daemon_die_timeout_secs" == 0 ) ]]; do
echo "$run_time"
(( run_time++ ))
sleep 1
[[ "$fake_daemon_dying" == "true" ]] \
&& (( fake_daemon_die_timeout_secs-- ))
done
exit "$fake_daemon_exit_code"
#!/bin/bash
echo "should take about 0 seconds with exit code 0"
time env fake_daemon_dying=true ./fake_daemon.sh
echo "exit code: $?"
echo
echo "should take about 3 seconds with exit code 5"
time env fake_daemon_dying=true fake_daemon_die_timeout_secs=3 fake_daemon_exit_code=5 ./fake_daemon.sh
echo "exit code: $?"
echo
echo "should die about 3 seconds after ^C with exit code 7"
time env fake_daemon_die_timeout_secs=3 fake_daemon_exit_code=7 ./fake_daemon.sh
echo "exit code: $?"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment