Using netcat/cat in a background shell script (How to avoid Stopped (tty input)? )

LovelyVirus picture LovelyVirus · Aug 12, 2011 · Viewed 24.1k times · Source

Abstract: How to run an interactive task in background?

Details: I am trying to run this simple script under ash shell (Busybox) as a background task.

myscript.sh&

However the script stops immediately...

[1]+ Stopped (tty input) myscript.sh

The myscript.sh contents... (only the relvant part, other then that I trap SIGINT, SIGHUP etc)

#!/bin/sh

catpid=0

START_COPY()
{
  cat /dev/charfile > /path/outfile &
  catpid = $! 
}

STOP_COPY()
{
  kill catpid 
}

netcat SOME_IP PORT | while read EVENT
do
  case $EVENT in
    start) START_COPY;;
    stop) STOP_COPY;;
  esac
done

From simple command line tests I found that bot cat and netcat try to read from tty. Note that this netcat version does not have -e to supress tty.

Now what can be done to avoid myscript becoming stopped?

Things I have tried so for without any success:

1) netcat/cat ... < /dev/tty (or the output of tty)

2) Running the block containing cat and netcat in a subshell using (). This may work but then how to grab PID of cat?

Over to you experts...


The problem still exists. A simple test for you all to try:

1) In one terminal run netcat -l -p 11111 (without &)

2) In another terminal run netcat localhost 11111 & (This should stop after a while with message Stopped (TTY input) )

How to avoid this?

Answer

darkuncle picture darkuncle · Jul 19, 2012

you probably want netcat's "-d" option, which tells it not to read from STDIN.