-
-
Save izabera/14e5d3b1c63abe076b42 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# source this with bash | |
declare -A cprc_{write,read,pids} | |
cprc () { | |
if [[ -v 'cprc_write[$1]' ]]; then | |
echo cprc exists >&2 | |
return 1 | |
elif [[ -z $1 ]]; then | |
echo invalid name >&2 | |
return 1 | |
else | |
mkfifo "/tmp/cprc$1" && | |
exec {cprc_write[$1]}> >(eval "$2" > "/tmp/cprc$1") && | |
exec {cprc_read[$1]}< "/tmp/cprc$1" && | |
rm "/tmp/cprc$1" | |
cprc_pids[$1]=$! | |
fi | |
} | |
cprc_write () { | |
if [[ ! -v 'cprc_write[$1]' ]]; then | |
echo cprc does not exist >&2 | |
return 1 | |
else | |
printf "%s\n" "$2" >&"${cprc_write[$1]}" | |
fi | |
} | |
cprc_read () { | |
if [[ ! -v 'cprc_write[$1]' ]]; then | |
echo cprc does not exist >&2 | |
return 1 | |
else | |
read -r -u "${cprc_read[$1]}" | |
fi | |
} | |
trap 'kill "${cprc_pids[@]}"' EXIT | |
cprc foo 'echo "$(echo "foo: hello world!")"; cat' | |
cprc bar 'echo "$(echo "bar: hello world!")"; cat' | |
cprc_write foo "foo: hi world" | |
cprc_write bar "bar: hi world" | |
cprc_read bar | |
declare -p REPLY | |
cprc_read foo | |
declare -p REPLY | |
cprc_read foo | |
declare -p REPLY | |
cprc_read bar | |
declare -p REPLY |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment