在 fifo 管道中添加行尾或换行符

Add end of line or new line character in fifo pipe

我想实现一个实用程序,我可以在其中捕获 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[=10=]\x01[=10=][=10=][=10=]\x1C\x04\x4C[=10=][=10=][=10=][=10=][=10=][=10=]" > inputPipe
#continuously looking for server response and then after reading the response, again querying 
#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[=10=]\x01[=10=][=10=][=10=]\x1C\x05\x15[=10=][=10=][=10=][=10=][=10=][=10=]" > inputPipe
    fi 
  done <outputPipe
trap "rm -f inputPipe outputPipe" EXIT 
trap "kill -9 $pid1 $pid2 $pid3" EXIT

尝试只打开一次输入管道,(同时打开输出管道):

{
    echo -e "\x5A\x01[=10=]\x01[=10=][=10=][=10=]\x1C\x04\x4C[=10=][=10=][=10=][=10=][=10=][=10=]" >&3

    while true;  do 
        if read line; then 
            echo "$line"
            sleep 2
            echo -e "\x5A\x01[=10=]\x01[=10=][=10=][=10=]\x1C\x05\x15[=10=][=10=][=10=][=10=][=10=][=10=]" >&3
        fi 
    done 
} <outputPipe 3>inputPipe

同时考虑使用 -r 选项 read

不妨删除 cat:

nc -v 192.168.1.105 19204 > outputPipe <inputPipe &

如果这不起作用,请考虑实施 Coproc