Using named pipes to create a 'loop'

独自空忆成欢 提交于 2019-12-24 08:03:58

问题


I'm very new to shell scripting and I am trying to get to grips with piping. I could be heading in completely the wrong direction here...

What I have is a shell script that contains a simple while true loop, within this loop I am getting netcat to listen on a specified port and piping input to a binary file that is awaiting for commands through stdin. This is Script-A

I have a second shell script that accepts input as arguments, it then echos those arguments to the port that netcat is listening on. This is Script-B

My aim is to get the returning output from the binary file located in Script-A into Script-B via Netcat so that it can be returned via stdout. The binary file has to be initialized and awaiting input.

This is what I have:

Script-A

while true; do
    nc -kl 1234 | /binarylocation/ --readargumentsfromstdinflag
done

Script-B

foo=$(echo "$*" | nc localhost 1234)
echo "$foo"

With this setup, the output of the binary file is done via Script-A After doing some research I got to this point, I am trying to use a named pipe to create a sort of loop from the binary file back to netcat, it's still not working -

Script-A

mkfifo foobar

while true; do
    nc -kl 1234 < foobar | /binarylocation/ --readargumentsfromstdinflag > foobar
done

Script-B hasn't changed.

Bear in mind my shell scripting experience stems over a period of about a single day, thank you.


回答1:


The problem is in your script B.. netcat reads from STDIN and exits immediately when STDIN is closed, not waiting for the response.

you will realize when you do this:

foo=$( ( echo -e "$*"; sleep 2 ) | nc localhost 1234) 
echo "$foo"

nc has a parameter for the stdin behaviour..

 -q    after EOF on stdin, wait the specified number of seconds and 
       then quit. If seconds is negative, wait forever.`

So you should do:

foo=$( echo -e "$*" | nc -q5 localhost 1234) 
echo "$foo"


来源:https://stackoverflow.com/questions/9376830/using-named-pipes-to-create-a-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!