我有两个进程需要这样连接:
proc1 -- 将输出发送到 proc2 proc2 -- 将输出发送到 proc1
到目前为止,所有的管道例子都是这样的: proc1 |过程2
这很好,但是我如何让 proc2 的输出转到 proc1?
一个 bash 例子会很好。 Windows shell 示例会很棒 :)
提前致谢, 阿德里安。
添加更多细节:
该系统有望作为客户端-服务器系统工作,其中客户端在请求-响应交互模型中与服务器一起工作。当客户端没有更多请求时,交互结束。
交互示例: 客户:请求1; 服务器:response1; 客户:请求2; 服务器:response2; . . . . 客户端:关闭请求; 服务器:closeApproved;
此时服务器在客户端退出后退出。示例结束。
似乎有一个解决方案(假设管道可用) 客户端 < 管道 |服务器 > 管道 不会工作(请纠正我)因为在这种安排中,客户端产生一个大请求,shell 将这个大请求通过管道传递给服务器,然后服务器产生一个大响应,最后 shell 将这个大响应通过管道传递给客户端。
最佳答案
看起来 bash coprocess 可能就是您想要的。在 bash 手册中查找 coproc
保留字。
(编辑:添加简单的使用方案)
它是这样工作的:
# start first process as a coprocess to the current shell
coproc proc1
# now ${COPROC[0]} contains the number of an open (input) file descriptor
# connected to the output of proc1, and ${COPROC[1]} the number of an
# open (output) file descriptor connected to the input of proc1.
# start second process, connecting its input- and outputstreams
# to the output- and inputstreams of the first process
proc2 <&${COPROC[0]} >&${COPROC[1]}
# wait on the first process to finish.
wait $COPROC_PID
如果您可能有多个协同进程,请为您的进程命名,如下所示:
coproc NAME {
proc1
}
然后你可以在之前使用过COPROC
的地方使用NAME
。
这是一个完整的示例程序,它使用 ping
函数作为 proc1 和 proc2:
#!/bin/bash
#
# Example program using a bash coprocess to run two processes
# with their input/output streams
#
#
# A function which reads lines of input and
# writes them back to standard output with the
# first char cut off, waiting 5s inbetween.
#
# It finishes whenever an empty line is read or written,
# or at end-of-file.
#
# The parameter $1 is used in debugging output on stderr.
#
function ping ()
{
while read
do
local sending
echo "ping $1: received '$REPLY'" >&2
[[ -n $REPLY ]] || break
sleep 5s
sending=${REPLY:1}
echo "ping $1: sending '$sending'" >&2
echo $sending
[[ -n $sending ]] || break
done
echo "ping $1: end" >&2
}
#
# Start first ping process as a coprocess with name 'p1'.
#
coproc p1 {
ping 1
}
# send some initial data to p1. (Not needed if one of the processes
# starts writing before first reading.)
echo "Hello World" >&${p1[1]}
sleep 2.5s
#
# Run second ping process, connecting its default input/output
# to the default output/input of p1.
#
ping 2 <&${p1[0]} >&${p1[1]}
# wait for the coprocess to finish too.
wait $p1_PID
它使用 shell 函数的两次调用而不是外部程序,但它也适用于此类程序。这是输出(在 stderr 上):
ping 1: received 'Hello World'
ping 1: sending 'ello World'
ping 2: received 'ello World'
ping 2: sending 'llo World'
ping 1: received 'llo World'
ping 1: sending 'lo World'
ping 2: received 'lo World'
ping 2: sending 'o World'
ping 1: received 'o World'
ping 1: sending ' World'
ping 2: received 'World'
ping 2: sending 'orld'
ping 1: received 'orld'
ping 1: sending 'rld'
ping 2: received 'rld'
ping 2: sending 'ld'
ping 1: received 'ld'
ping 1: sending 'd'
ping 2: received 'd'
ping 2: sending ''
ping 2: end
ping 1: received ''
ping 1: end
关于bash - 如何将第二个进程的标准输出重定向回第一个进程的标准输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5129276/