且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用"coproc"与另一个命令驱动程序进行交互

更新时间:2023-11-03 20:10:10

result = $(echo 'command' <&${bkgndProc[0]})    ### Doesn't work for me

至少基本上不会工作,因为上面有空格

wouldn't work at least basically since you have spaces on it

result=$(echo 'command' <&${bkgndProc[0]})

----更新----

---- Update ----

一个简单的概念可以显示在这样的脚本中:

A simple concept could be shown in a script like this:

#!/bin/bash

# create the co-process
coproc myproc {
    bash
}

# send a command to it (echo a)
echo 'echo a' >&"${myproc[1]}"

# read a line from its output
read line <&"${myproc[0]}"

# show the line
echo "$line"

输出:

a

另一个使用超时读取多行的代码:

Another which reads multiple lines using a timeout:

#!/bin/bash

coproc myproc {
    bash
}

# send a command to message 4 random numbers in 4 lines
echo 'echo "$RANDOM"; echo "$RANDOM"; echo "$RANDOM"; echo "$RANDOM"' >&"${myproc[1]}"

# keep reading the line until it times out
while read -t 1 -u "${myproc[0]}" line; do
    echo "$line"
done

输出:

17393
1423
8368
1782

如果我们使用 cat ,它将不再退出,因为另一端仍处于活动状态且已连接,并且尚未达到EOF.这就是我们使用超时的原因.

If we use cat, it would no longer quit since the other end is still alive and connected, and EOF is not yet reached. It's the reason why we used timeouts.

cat <&"${myproc[0]}"