Skip to content

Instantly share code, notes, and snippets.

@akesterson
Created October 22, 2013 12:15
Show Gist options
  • Select an option

  • Save akesterson/7099555 to your computer and use it in GitHub Desktop.

Select an option

Save akesterson/7099555 to your computer and use it in GitHub Desktop.
killtree() {
# Stolen from stack overflow
local _pid=$1
local _sig=${2:-TERM}
kill -stop ${_pid} 2>/dev/null # needed to stop quickly forking parent from producing child between child killing and parent killing
for _child in $(ps -o pid --no-headers --ppid ${_pid}); do
killtree ${_child} ${_sig}
done
kill -${_sig} ${_pid} 2>/dev/null
}
function killjobs
{
if [[ "${cmdarg_cfg['verbose']}" == "true" ]]; then
echo 'Doing my best to kill all the background jobs, please wait...' >&2
jobs -l >&2
echo >&2
fi
for idx in ${!background_jobs[@]};
do
job=${background_jobs[$idx]}
if [[ "${cmdarg_cfg['verbose']}" == "true" ]]; then
echo "Killing $job" >&2
fi
killtree $job
done
}
function trap_control_c
{
if [ $LASTCTRLC -ne 0 ] && [ $(expr $(date "+%s") - $LASTCTRLC) -le 2 ]; then
killjobs
return
fi
ps wwfx -p $$ >&2
echo >&2
echo "Press Ctrl+C again within 2 seconds to quit" >&2
LASTCTRLC=$(date "+%s")
}
trap trap_control_c SIGINT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment