#!/bin/bash

coprocess_term ()
{

  exec 3>&- 4<&-
  return $?

}

coprocess_init ()
{

  fifo=/tmp/coprocess.$$.$RANDOM

  rm -f $fifo.i $fifo.o
  mkfifo "$fifo.i" || return $?
  mkfifo "$fifo.o" || return $?

  ( "$@" <$fifo.i >$fifo.o ; rm -f $fifo.i $fifo.o ) &
  exec 3>$fifo.i 4<$fifo.o || return $?

# ****************************************************************
# Solaris: Hangs
# Cygwin: Server never ends
#
# exec 3>$fifo.i 4<$fifo.o || return $?
# ( "$@" <$fifo.i >$fifo.o ; rm -f $fifo.i $fifo.o ) &
# ****************************************************************
# Solaris: Works fine
# Cygwin: Hangs
#
# ( "$@" <$fifo.i >$fifo.o ; rm -f $fifo.i $fifo.o ) &
# exec 3>$fifo.i 4<$fifo.o || return $?
# ****************************************************************
# Solaris: Not tested
# Cygwin: Works fine (but 5 seconds too slow)
#
# ( "$@" <$fifo.i >$fifo.o ; rm -f $fifo.i $fifo.o ) &
# sleep 5
# exec 3>$fifo.i 4<$fifo.o || return $?
# ****************************************************************

  return 0

}

coprocess_put ()
{

  echo "$@" >&3
  return $?

}

coprocess_get ()
{

  read "$@" <&4
  return $?

}

coprocess_test_1_server ()
{

  echo "coprocess_test_1_server: start" 1>&2

  while read REPLY ; do
    echo "$REPLY =" `expr $REPLY`
  done

  echo "coprocess_test_1_server: end" 1>&2

}

coprocess_test_1_client ()
{

  coprocess_init coprocess_test_1_server
  echo "coprocess_test_1_client: init rc: $?" 1>&2

  while read REPLY ; do
    coprocess_put $REPLY
    echo "coprocess_test_1_client: put rc: $?" 1>&2
    coprocess_get REPLY
    echo "coprocess_test_1_client: get rc: $?" 1>&2
    echo "coprocess_test_1_client: REPLY: $REPLY" 1>&2
  done

  coprocess_term
  echo "coprocess_test_1_client: term rc: $?" 1>&2

}

echo 1 + 1 | coprocess_test_1_client
