问题
I have two processes that interface with one another over stdin and stdout.
Suppose I have process A and process B. The stdout of B needs to feed into the stdin of A, and the stdout of A needs to feed in to that of process B.
Is there a simple way to express this relationship in a simple command, or is there a basic shell script that can enable this?
Thanks in advance.
回答1:
Take a look at named pipes. Create one pipe for A to B, and one pipe for B to A. Then start A with its stdout redirected to the first, and its stdin redirected to the second. Then start B with the opposite.
It would look something like this:
mkfifo --mode=0666 /tmp/AtoB
mkfifo --mode=0666 /tmp/BtoA
A < BtoA > AtoB
B < AtoB > BtoA
add: Of course, they'll need some way to recognize that both parties are present. Something like a simple "I am here, are you?" that both receive a response to.
Important: As noted in comments below, this process will deadlock with both programs blocking on reads. Some form of coordination will be necessary to ensure this doesn't happen.
回答2:
Bash 4 introduces coproc:
declare -a FDS
coproc FDS { process_A; }
process_B <&${FDS[0]} >&${FDS[1]}
回答3:
(I would comment on Keith's answer, but don't have enough rep yet.)
Testing this on OpenBSD, I found it impossible to start the scripts by running:
./a < btoa > atob &
./b < atob > btoa
(atob
and btoa
being FIFOs, and the scripts a
and b
duplicating stdin)
However, after also backgrounding the second one, as soon as I ran > btoa
in my shell (the null command, however opening btoa
for writing), they started. (Beware the infinite loop!) I guess this means you need a third process.
I'm not sure if the behavior of FIFOs in such cases (e.g. multiple processes opening for writing) is standardized.
来源:https://stackoverflow.com/questions/9689498/feedback-stdin-and-stdout-of-two-processes