Bash – Running piped bash script in background

background-processbashdaemonpipe

I'm attempting to build a monitoring script to watch localhost communication using netcat. I have two scripts that I've built, one to start the monitoring loop and one for the loop itself. They are as follows :

start.sh

#!/bin/bash
netcat localhost 1099  | bash loop.sh &

loop.sh

#!/bin/bash
while read sInput; do
     ...do something with $sInput
done

Simply running this application without in the foreground works fine but as soon as I try to run this script in the background it goes from running to stopped instantly. Could someone please educate me as to why this is happening and how to alleviate the problem.

My end goal is to have a bash script that I can create an arch linux daemon script with and have everything work perfectly. Your help is appreciated.

Best Answer

Sounds like it's reading from standard input (stdin). Try adding the -d (Do not attempt to read from stdin) option to netcat. Or redirect on the command line:

netcat localhost 1099 <&- | bash loop.sh &

You may also want to use nohup to make sure that it won't be adversely affected when/if you exit that shell before it stops.

Related Question