Skip to content

Instantly share code, notes, and snippets.

@d630
Last active November 10, 2016 22:47
Show Gist options
  • Save d630/70bccfcae262bbfe30fd870d71733ade to your computer and use it in GitHub Desktop.
Save d630/70bccfcae262bbfe30fd870d71733ade to your computer and use it in GitHub Desktop.
bash: send stdout to a handler in a process substitution via exec and wait for it to be finished with processing input (SIGSTOP/SIGCONT)
#!/usr/bin/env bash
function setup {
typeset -g "$1" 2>/dev/null && {
typeset -n fd=$1;
((${!fd})) &&
exec {fd}>&-;
exec {fd}> >('handler');
};
};
function msg {
if
((${1:?}));
then
typeset fd=${!1};
fd=${fd:?};
else
return 1;
fi;
shift 1;
[[ -f /dev/stdin || -p /dev/stdin ]] &&
cat /dev/stdin 1>&${fd};
(($#)) &&
printf '%s\n' "$@" 1>&${fd};
};
function sig_stop {
kill -s SIGSTOP "${1:-$$}";
};
function sig_cont {
kill -s SIGCONT "${1:-$$}";
};
# -- MAIN.
set +m;
# an example
echo Nr 1.;
(
function handler {
ti_red_f=$(tput setaf 1);
ti_reset="$(tput sgr0 || tput me)";
while
IFS= read -r;
do
case $REPLY in
(resume' '?*)
'sig_cont' ${REPLY#resume };
continue;
esac;
sleep .5;
printf '%s\n' "${ti_red_f}${REPLY}${ti_reset}";
done;
};
read -r pid _ < /proc/self/stat;
echo bang!;
echo;
'setup' myfd;
printf '%s\n' foo bar |
'msg' myfd "fo o" bar "resume $pid" &
'sig_stop' $pid;
echo;
echo resuuumed!;
);
set -m;
# vim: set ts=4 sw=4 tw=0 et :
@d630
Copy link
Author

d630 commented Nov 8, 2016

$ x.sh
$ . x.sh
$ (. x.sh)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment