Hacker News new | ask | show | jobs
by Klasiaster 1625 days ago
This here is a simple echo server that uses tr to uppercase:

  exec {checkfd}>/dev/null
  CHECKFDPATH="/proc/$$/fd/${checkfd}"
  (while [ -e "$CHECKFDPATH" ]; do sleep 1; done) > >(true) &
  STDINPID="$!"
  WRITER="/proc/$STDINPID/fd/1"
  
  while IFS= read -r LINE; do
    # only echo lines if we didn't close the connection yet
    if [ -e "$CHECKFDPATH" ]; then
      echo "$LINE" | tr '[:lower:]' '[:upper:]' > "$WRITER"
      if [ "$LINE" = "bye" ]; then
        exec {checkfd}<&-
      fi
    else
      echo "received while closed: $LINE"
    fi
  done < <(nc -q 1 -l 8080 < "$WRITER")
  if [ -e "$CHECKFDPATH" ]; then
    # close checkfd to close writer pipe
    exec {checkfd}<&-
  fi
1 comments

This variant here works a bit different:

  exec {checkfd}>/dev/null
  CHECKFDPATH="/proc/$$/fd/${checkfd}"
  (while [ -e "$CHECKFDPATH" ]; do sleep 1; done) > >(true) &
  STDINPID="$!"
  disown "$STDINPID"
  READER="/proc/$STDINPID/fd/1"
  
  { while IFS= read -r LINE; do
    echo "$LINE" | tr '[:lower:]' '[:upper:]'
    if [ "$LINE" = "bye" ]; then
      echo exiting > /dev/stderr
      break
    fi
  done < "$READER" ; kill -9 "$STDINPID" 2>/dev/null || true ; } | { nc -q 1 -l 8080 > "$READER" ; kill -9 "$STDINPID" 2>/dev/null || true ; }
  exec {checkfd}<&-