Compare commits

..

2 Commits

Author SHA1 Message Date
olli
05475361e8 fixes 2024-06-25 12:11:46 +02:00
olli
ae1379180c fixes 2024-06-25 12:10:19 +02:00

View File

@ -1,66 +1,34 @@
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
local g_calc_jobs g_rnd
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}" ]
# check if bc is already running
if [[ -z "$g_fd_bc_in" || -z "$g_fd_bc_out" ]]
then
g_kill_all_background_jobs bc-ql
g_kill_all_background_jobs sed
g_rnd=$$
mkdir -p ${g_tmp}/${g_rnd}
[ -p ${g_tmp}/${g_rnd}/bc-in ] || mkfifo ${g_tmp}/${g_rnd}/bc-in
[ -p ${g_tmp}/${g_rnd}/bc-out ] || mkfifo ${g_tmp}/${g_rnd}/bc-out
[ -p ${g_tmp}/${g_rnd}/bc-sed-in ] || mkfifo ${g_tmp}/${g_rnd}/bc-sed-in
[ -p ${g_tmp}/${g_rnd}/bc-sed-out ] || mkfifo ${g_tmp}/${g_rnd}/bc-sed-out
# bc stream channel
{ bc -ql <${g_tmp}/${g_rnd}/bc-in 2>&1 >${g_tmp}/${g_rnd}/bc-out & } 2>/dev/null
exec 3>${g_tmp}/${g_rnd}/bc-in 4<${g_tmp}/${g_rnd}/bc-out
# sed stream channel
{ 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"
local bc_input="$g_tmp/$$-g_bc_input"
local bc_output="$g_tmp/$$-g_bc_output"
# create fifo pipe
[ -p "$bc_input" ] || mkfifo "$bc_input"
[ -p "$bc_output" ] || mkfifo "$bc_output"
# run bc in background und switch i/o to pipes
bc -ql < "$bc_input" > "$bc_output" 2>&1 &
# store in filedescriptiors
exec {g_fd_bc_in}> "$bc_input"
exec {g_fd_bc_out}< "$bc_output"
fi
# do bc
echo "scale=8; $@" >&3
local g_bc_out
if ! read -t 0.1 g_bc_out <&4
# send calculation and read result
echo "$1" >&${g_fd_bc_in}
read -u ${g_fd_bc_out} g_calc_result
g_calc_result=${g_calc_result//-./-0.}
g_calc_result=${g_calc_result//./0.}
if ! g_num_valid_number $g_calc_result
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
echo "${FUNCNAME} $@" 1>&2
unset g_calc_result
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
fi
# store result
g_calc_result=$g_sed_out
}