【问题标题】:Add end of line or new line character in fifo pipe在 fifo 管道中添加行尾或换行符
【发布时间】:2022-01-06 19:21:42
【问题描述】:

我想实现一个实用程序,我可以在其中捕获 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
#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\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

【问题讨论】:

    标签: linux bash shell pipe


    【解决方案1】:

    尝试只打开一次输入管道,(并与输出管道一起打开):

    {
        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 选项用于read

    还不如去掉cat:

    nc -v 192.168.1.105 19204 > outputPipe <inputPipe &
    

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

    【讨论】:

    • 非常感谢@konsolebox 我以另一种方式修复了它,我知道我的 TCP 响应的第一个字节总是 0x5A 所以读取该字符的行,然后从响应中删除 TCP 标头前缀,因为我知道我的响应正文总是从“{”字符开始。虽然是真的;如果读取 -r -d$'\x5A' 行则执行;然后 tmp=${line#*\{} tchar='{' fstr="${tchar}${tmp}" 清除 echo $fstr;睡觉 2; echo -e "\x5A\x01\0\x01\0\0\0\x1C\x04\x4C\0\0\0\0\0\0" >&3 fi done inputPipe 你的输入真的有帮助我很多。非常感谢。
    猜你喜欢
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 2015-11-01
    相关资源
    最近更新 更多