title: Using netcat/cat in a background shell script (How to avoid Stopped (tty input)? )
body: <p>Abstract: How to run an interactive task in background?</p>
  
  <p>Details: I am trying to run this simple script under ash shell (Busybox) as a background task.</p>
  
  <blockquote>
    <p>myscript.sh&amp;</p>
  </blockquote>
  
  <p>However the script stops immediately...</p>
  
  <blockquote>
    <p>[1]+  Stopped (tty input) myscript.sh</p>
  </blockquote>
  
  <p>The myscript.sh contents... (only the relvant part, other then that I trap SIGINT, SIGHUP etc)</p>
  
  <pre><code>#!/bin/sh
  
  catpid=0
  
  START_COPY()
  {
    cat /dev/charfile &gt; /path/outfile &amp;
    catpid = $! 
  }
  
  STOP_COPY()
  {
    kill catpid 
  }
  
  netcat SOME_IP PORT | while read EVENT
  do
    case $EVENT in
      start) START_COPY;;
      stop) STOP_COPY;;
    esac
  done
  </code></pre>
  
  <p>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.</p>
  
  <p>Now what can be done to avoid myscript becoming stopped?</p>
  
  <p>Things I have tried so for without any success:</p>
  
  <p>1) netcat/cat ... &lt; /dev/tty  (or the output of <code>tty</code>)</p>
  
  <p>2) Running the block containing cat and netcat in a subshell using (). This may work but then how to grab PID of cat?</p>
  
  <p>Over to you experts...</p>
  
  <hr>
  
  <p>The problem still exists. 
  A simple test for you all to try:</p>
  
  <p>1) In one terminal run netcat -l -p 11111 (without &amp;)</p>
  
  <p>2) In another terminal run netcat localhost 11111 &amp;  (This should stop after a while with message Stopped (TTY input) )</p>
  
  <p>How to avoid this?</p>