Ответ 1
Похоже, что сопроцессор bash может быть тем, что вы хотите. Найдите coproc
зарезервированное слово в руководстве bash.
(Изменить: добавление простой схемы использования)
Он работает следующим образом:
# 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
}
Затем вы можете использовать NAME
везде, где раньше использовался coproc
.
Вот полная примерная программа, использующая функцию 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
Он использует две вызовы функции оболочки вместо внешних программ, но она также будет работать с такими программами. Вот вывод (на 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