如何使用"coproc"与另一个命令驱动程序进行交互 [英] How to use 'coproc' to interact with another command driven program
问题描述
好吧,显然我不是bash大师,需要一个!
Ok, obviously I am NOT a bash guru and am in need of one!
我以前从未使用过'coproc',但这似乎正是我所需要的.但是,我必须承认,我无法从各种"ping"示例中推断出![我尝试了几个小时...]
I have never used 'coproc' before, but it seems to be just what I need. But, I have to admit that I can not extrapolate from the various 'ping' examples out there! [I did try for a couple of hours...]
我要做的就是启动一个"coproc" shell脚本,该脚本可以从标准输入中获取输入并将其结果写到标准输出中.我希望主脚本分别发送和处理这些命令和结果.
All I want to do is to start a 'coproc' shell script that can take input from standard in and writes it's results to standard out. I want the main script to do the sending and processing of those commands and results respectively.
这是我尝试做的最简单的概述之一:使用更详细的内容进行编辑
Here is one of the simplest outlines of what I am trying to do: EDITED WITH BETTER DETAIL
#! /bin/bash
coproc bkgndProc {
/some/path/to/usefulScript.sh maybeSomeArgsHere
}
// send command #1 to bkgndProc here
result=$(echo 'command' <&${bkgndProc[0]}) ### Doesn't work for me
echo "Did it work? $result" ### this just prints back the 'command' I used
// here execute conditional logic based on result:
// if result1; then
// send command #2 here, getting results
// else
// send command #3 here, again getting results
// fi
很抱歉使用上面的伪代码,但是我不确定那些发送命令应该是什么!如果有人可以提供详细信息,将不胜感激!
Sorry about using pseudo-code above, but I'm not sure what those sending commands should be! If anyone could supply the details that would be greatly appreciated!
推荐答案
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]}"
这篇关于如何使用"coproc"与另一个命令驱动程序进行交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!