Anthony Stansbridge
Anthony Stansbridge

Reputation: 55

Using named pipes to create a 'loop'

I'm very new to shell scripting and I am trying to get to grips with piping. I could be heading in completely the wrong direction here...

What I have is a shell script that contains a simple while true loop, within this loop I am getting netcat to listen on a specified port and piping input to a binary file that is awaiting for commands through stdin. This is Script-A

I have a second shell script that accepts input as arguments, it then echos those arguments to the port that netcat is listening on. This is Script-B

My aim is to get the returning output from the binary file located in Script-A into Script-B via Netcat so that it can be returned via stdout. The binary file has to be initialized and awaiting input.

This is what I have:

Script-A

while true; do
    nc -kl 1234 | /binarylocation/ --readargumentsfromstdinflag
done

Script-B

foo=$(echo "$*" | nc localhost 1234)
echo "$foo"

With this setup, the output of the binary file is done via Script-A After doing some research I got to this point, I am trying to use a named pipe to create a sort of loop from the binary file back to netcat, it's still not working -

Script-A

mkfifo foobar

while true; do
    nc -kl 1234 < foobar | /binarylocation/ --readargumentsfromstdinflag > foobar
done

Script-B hasn't changed.

Bear in mind my shell scripting experience stems over a period of about a single day, thank you.

Upvotes: 1

Views: 1512

Answers (1)

Kaii
Kaii

Reputation: 20540

The problem is in your script B.. netcat reads from STDIN and exits immediately when STDIN is closed, not waiting for the response.

you will realize when you do this:

foo=$( ( echo -e "$*"; sleep 2 ) | nc localhost 1234) 
echo "$foo"

nc has a parameter for the stdin behaviour..

 -q    after EOF on stdin, wait the specified number of seconds and 
       then quit. If seconds is negative, wait forever.`

So you should do:

foo=$( echo -e "$*" | nc -q5 localhost 1234) 
echo "$foo"

Upvotes: 1

Related Questions