Compare commits

..

No commits in common. "05475361e800d53f3bab518cff5d999da2de38d7" and "567a3ae1a9d8169c99ee7dd3e9c40cf184a942d0" have entirely different histories.

View File

@ -1,34 +1,66 @@
function g_calc { function g_calc {
# function for calculating via bc running in the background (much faster then starting bc every time)
# $g_fd_bc_in $fd_bc_out have to be global
unset g_calc_result unset g_calc_result
# check if bc is already running local g_calc_jobs g_rnd
if [[ -z "$g_fd_bc_in" || -z "$g_fd_bc_out" ]] local g_bc_running=true
mapfile -t g_calc_jobs < <(jobs -r)
g_calc_jobs_v=${g_calc_jobs[*]}
[[ $g_calc_jobs_v =~ bc ]] || unset g_bc_running
# Use bc in backround for multiple bc's running much faster
if [ -z "${g_bc_running}" ]
then then
local bc_input="$g_tmp/$$-g_bc_input"
local bc_output="$g_tmp/$$-g_bc_output" g_kill_all_background_jobs bc-ql
# create fifo pipe g_kill_all_background_jobs sed
[ -p "$bc_input" ] || mkfifo "$bc_input"
[ -p "$bc_output" ] || mkfifo "$bc_output" g_rnd=$$
# run bc in background und switch i/o to pipes mkdir -p ${g_tmp}/${g_rnd}
bc -ql < "$bc_input" > "$bc_output" 2>&1 & [ -p ${g_tmp}/${g_rnd}/bc-in ] || mkfifo ${g_tmp}/${g_rnd}/bc-in
# store in filedescriptiors [ -p ${g_tmp}/${g_rnd}/bc-out ] || mkfifo ${g_tmp}/${g_rnd}/bc-out
exec {g_fd_bc_in}> "$bc_input" [ -p ${g_tmp}/${g_rnd}/bc-sed-in ] || mkfifo ${g_tmp}/${g_rnd}/bc-sed-in
exec {g_fd_bc_out}< "$bc_output" [ -p ${g_tmp}/${g_rnd}/bc-sed-out ] || mkfifo ${g_tmp}/${g_rnd}/bc-sed-out
fi
# send calculation and read result # bc stream channel
echo "$1" >&${g_fd_bc_in} { bc -ql <${g_tmp}/${g_rnd}/bc-in 2>&1 >${g_tmp}/${g_rnd}/bc-out & } 2>/dev/null
read -u ${g_fd_bc_out} g_calc_result exec 3>${g_tmp}/${g_rnd}/bc-in 4<${g_tmp}/${g_rnd}/bc-out
g_calc_result=${g_calc_result//-./-0.}
g_calc_result=${g_calc_result//./0.} # sed stream channel
if ! g_num_valid_number $g_calc_result { sed -su 's/^\./0./; s/^-\./-0./' <${g_tmp}/${g_rnd}/bc-sed-in >${g_tmp}/${g_rnd}/bc-sed-out & } 2>/dev/null
exec 5>${g_tmp}/${g_rnd}/bc-sed-in 6<${g_tmp}/${g_rnd}/bc-sed-out
g_bc_running="true"
fi
# do bc
echo "scale=8; $@" >&3
local g_bc_out
if ! read -t 0.1 g_bc_out <&4
then then
echo "${FUNCNAME} $@" 1>&2 g_traceback "$@"
unset g_calc_result ( exec 3<&- ) 2>/dev/null
( exec 4<&- ) 2>/dev/null
( exec 5<&- ) 2>/dev/null
( exec 6<&- ) 2>/dev/null
#unset g_bc_running
return 1
fi
# do sed
echo ${g_bc_out} >&5
local g_sed_out
if ! read -t 0.1 g_sed_out <&6
then
g_traceback "$@"
( exec 3<&- ) 2>/dev/null
( exec 4<&- ) 2>/dev/null
( exec 5<&- ) 2>/dev/null
( exec 6<&- ) 2>/dev/null
#unset g_bc_running
return 1 return 1
fi fi
}
# store result
g_calc_result=$g_sed_out
}