2

I made a simple server using netcat and backpipe:

mkfifo backpipe
nc -l 8080 < backpipe | parseRequests.sh > backpipe

The contents of "parseRequests.sh" is just:

#!/bin/sh
if [ "$1" = "1+1" ]; then echo "2"; else echo "0"; fi

When I connected to this server in another machine using

nc 10.0.0.2 8080

The connection ended immediately with "0" returned.

My question is, how can I keep the connection so that I can type many requests in the client side? If I use 'tee log.txt' instead of 'parseRequests.sh', the connection can be kept alive. I guess the 'echo' command in the "parseRequests.sh" sent an EOF signal to nc, which caused nc to quit immediately. How can I avoid this?

I know I can listen to requests on one port and send answers back using another port in a loop. But I prefer to keep the same port alive for both requests and answers.

1 Answer 1

5

The program on the left side of a pipe does not receive an EOF (which is not a signal) when the right side of the pipeline ends. It gets a SIGPIPE which tells it to terminate. The problem is that you are not reading anything from the pipeline or reading any data from the pipeline. You probably want a while read loop which will read from stdin as long as it's alive:

while read -r value; do
    if [ "$value" = "1+1" ]; then 
        echo "2";
    else
        echo "0";
    fi
done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .