Skip to content

Instantly share code, notes, and snippets.

@izabera
Created October 31, 2015 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save izabera/14e5d3b1c63abe076b42 to your computer and use it in GitHub Desktop.
Save izabera/14e5d3b1c63abe076b42 to your computer and use it in GitHub Desktop.
#!/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