Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 719
LovelyVirus Avatar asked Aug 12 '11 15:08

LovelyVirus


People also ask

What is netcat used for?

Netcat functions as a back-end tool that allows for port scanning and port listening. In addition, you can actually transfer files directly through Netcat or use it as a backdoor into other networked systems.


2 Answers

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

like image 89
darkuncle Avatar answered Oct 25 '22 03:10

darkuncle


I can confirm that -d will help netcat run in the background.

I was seeing the same issue with:

nc -ulk 60001 | nc -lk 60002 &

Every time I queried the jobs, the pipe input would stop.

Changing the command to the following fixed it:

nc -ulkd 60001 | nc -lk 60002 &
like image 29
Dale Avatar answered Oct 25 '22 04:10

Dale