Commit 14997f20 by Eric Coissac

Generalize the management of signals

parent 5e2222f6
......@@ -12,20 +12,9 @@
include logging
logdebug "Load atexit package"
include stacks
newstack __LECABASHLIB_ATEXITSTACK__
function __atexit__manager__() {
loginfo "Cleanning the resources"
while popvalue __LECABASHLIB_ATEXITSTACK__ cmd ; do
eval "$cmd"
done
loginfo "Done."
}
include signal
function registeratexit() {
pushvalue __LECABASHLIB_ATEXITSTACK__ "${*}"
registertrap EXIT "${*}"
}
trap "__atexit__manager__" EXIT ERR
#
# LECA Bash library
#
# The LECA bash library provides a set of function used for helping
# development of bash script mainly to write job script on the luke
# cluster
#
# The files from the LECA Bash library must be sourced from your main script
#
include logging
logdebug "Load trap package"
include stacks
__LECABASH__trap_signal_list__() {
echo $(kill -l \
| sed -E $'s/[ \t]+/@/g' \
| tr '@' '\n' \
| grep '^SIG' \
| sed 's/SIG//')
}
__LECABASH__trap_signal_code__() {
local signal=$1
echo $(kill -l \
| sed -E $'s/[ \t]+/@/g' \
| sed -E 's/\)@/ /g' \
| tr '@' '\n' \
| grep "SIG${signal}" \
| awk '{print $1}')
}
__LECABASH__signal_trap_stack_name__() {
local signal="$1"
local stackname="__LECABASH__signal_${signal}_trap_stack__"
echo $stackname
}
__LECABASH__trap_function__() {
local signal="$1"
local stackname="$(__LECABASH__signal_trap_stack_name__ ${signal})"
local code="$(__LECABASH__trap_signal_code__ $signal)"
loginfo "Signal ${signal} trapped"
if [[ $(stacksize $stackname) > 0 ]]; then
while popvalue "$stackname" cmd ; do
eval "$cmd"
done
loginfo "Commands registered on signal $signal run."
fi
exit "$((128 + code))"
}
__LECABASH__contains__() {
local e match="$1"
shift
for e in "$@"; do
[[ "$e" == "$match" ]] && return 0
done
return 1
}
# Create a trap for all signals
__LECABASH__register_trap_manager__() {
local signals=( $(__LECABASH__trap_signal_list__) )
local used_signal=( $(trap -p | awk '{print $NF}') )
for signal in "${signals[@]}"; do
if ! __LECABASH__contains__ "$s" "${used_signal[@]}"; then
local stackname="$(__LECABASH__signal_trap_stack_name__ ${signal})"
newstack $stackname
logdebug "Register trap for signal $signal"
trap "__LECABASH__trap_function__ $signal" "$signal"
fi
done
}
function registertrap() {
local signal=$1
shift
local stackname="$(__LECABASH__signal_trap_stack_name__ ${signal})"
loginfo "Register new command on $signal : ${*}"
pushvalue "$stackname" "${*}"
}
__LECABASH__register_trap_manager__
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment