I want to implement a utility where I can capture the TCP server response and print it on the terminal on some interval.
Please refer below the code
#!/bin/bash
#creating two fresh fifo pipe
rm -f inputPipe
mkfifo inputPipe
rm -f outputPipe
mkfifo outputPipe
#opening them
perl -e 'open(my $fh, ">", "inputPipe"); sleep 3600 while 1' &
pid1=$!
perl -e 'open(my $fh, ">", "outputPipe"); sleep 3600 while 1' &
pid2=$!
#whatever I will write into inputPipe should go to TCP server and response of
#Tcp server should capture in outputPipe
cat inputPipe | nc -v 192.168.1.105 19204 > outputPipe &
pid3=$!
#TCP buffer written into inputPipe that will go to TCP server and then server will respond
echo -e "\x5A\x01\0\x01\0\0\0\x1C\x04\x4C\0\0\0\0\0\0" > inputPipe
#continously looking for server response and then afer reading the response, again quering
#same information again after 2 seconds
while true;
do
**#main problem i am getting here while reading server response because in server response there are no any
#end of line or new character hence below read statement hanging for infinite.**
if read line;
then
echo $line;
sleep 2;
echo -e "\x5A\x01\0\x01\0\0\0\x1C\x05\x15\0\0\0\0\0\0" > inputPipe
fi
done <outputPipe
trap "rm -f inputPipe outputPipe" EXIT
trap "kill -9 $pid1 $pid2 $pid3" EXIT
CodePudding user response:
Try opening the input pipe only once, (and also open it together with the output pipe):
{
echo -e "\x5A\x01\0\x01\0\0\0\x1C\x04\x4C\0\0\0\0\0\0" >&3
while true; do
if read line; then
echo "$line"
sleep 2
echo -e "\x5A\x01\0\x01\0\0\0\x1C\x05\x15\0\0\0\0\0\0" >&3
fi
done
} <outputPipe 3>inputPipe
Also consider using -r option to read.
Might as well remove cat:
nc -v 192.168.1.105 19204 > outputPipe <inputPipe &
If this doesn't work, consider implementing a Coproc.
