在shell/bash中的两个命令之间连接输入和输出 [英] Connecting input _and_output between of two commands in shell/bash
问题描述
我有两个(UNIX)程序A和B,它们从stdin/stdout读取和写入.
I have two (UNIX) programs A and B that read and write from stdin/stdout.
我的第一个问题是如何将A的标准输出连接到B的标准输入,以及将B的标准输出连接到A的标准输入. B但是双向管道.我怀疑可以通过使用exec重定向来解决此问题,但我无法获取去工作.这些程序是交互式的,因此无法使用临时文件.
My first problem is how to connect the stdout of A to stdin of B and the stdout of B to the stdin of A. I.e., something like A | B but a bidirectional pipe. I suspect I could solve this by using exec to redirect but I could not get it to work. The programs are interactive so a temporary file would not work.
第二个问题是我想复制每个方向,并通过日志记录程序将重复的内容通过管道传送到stdout,以便我可以看到在程序之间传递的(基于文本行的)流量.如果可以解决第一个问题,在这里我可以不考虑tee>(...).
The second problem is that I would like to duplicate each direction and pipe a duplicate via a logging program to stdout so that I can see the (text-line based) traffic that pass between the programs. Here I may get away with tee >(...) if I can solve the first problem.
这两个问题似乎都应该有众所周知的解决方案,但我什么也找不到.
Both these problems seems like they should have well known solutions but I have not be able to find anything.
我希望使用POSIX shell解决方案,或者至少在cygwin的bash中可以使用的解决方案.
I would prefer a POSIX shell solution, or at least something that works in bash on cygwin.
感谢您的回答,我提出了以下解决方案. A/B命令使用nc侦听两个端口.日志记录程序使用sed(带有-u进行无缓冲处理).
Thanks to your answers I came up with the following solution. The A/B commands uses nc to listen to two ports. The logging program uses sed (with -u for unbuffered processing).
bash-3.2$ fifodir=$(mktemp -d)
bash-3.2$ mkfifo "$fifodir/echoAtoB"
bash-3.2$ mkfifo "$fifodir/echoBtoA"
bash-3.2$ sed -u 's/^/A->B: /' "$fifodir/echoAtoB" &
bash-3.2$ sed -u 's/^/B->A: /' "$fifodir/echoBtoA" &
bash-3.2$ mkfifo "$fifodir/loopback"
bash-3.2$ nc -l -p 47002 < "$fifodir/loopback" \
| tee "$fifodir/echoAtoB" \
| nc -l -p 47001 \
| tee "$fifodir/echoBtoA" > "$fifodir/loopback"
这侦听到端口47001和47002的连接,并将所有流量回显到标准输出.
This listens for connection to port 47001 and 47002 and echos all traffic to standard output.
在外壳2中执行:
bash-3.2$ nc localhost 47001
在外壳3中执行:
bash-3.2$ nc localhost 47002
现在在shell 2中输入的行将被写入shell 3,反之亦然,流量将被记录到shell 1,例如:
Now lines entered in shell 2 will be written to shell 3 and vice versa and the traffic logged to shell 1, something like:
B->A: input to port 47001
A->B: input to port 47002
以上内容已在Cygwin上进行了测试
The above has been tested on Cygwin
更新:几天后(!),以上脚本停止工作.显然,它可能会陷入僵局.答案中的一些建议可能更可靠.
Update: The script above stopped working after a few days(!). Apparently it can deadlock. Some of the suggestions in the answers may be more reliable.
推荐答案
http://bisqwit. iki.fi/source/twinpipe.html
这篇关于在shell/bash中的两个命令之间连接输入和输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!