我想實作一個實用程式,我可以在其中捕獲 TCP 服務器回應并每隔一段時間在終端上列印它。
請參考下面的代碼
#!/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
uj5u.com熱心網友回復:
嘗試只打開一次輸入管道,(并與輸出管道一起打開):
{
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
還可以考慮使用-r選項 to read。
還不如洗掉cat:
nc -v 192.168.1.105 19204 > outputPipe <inputPipe &
如果這不起作用,請考慮實施Coproc。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/405841.html
標籤:
上一篇:使用終端命令find洗掉擴展名
