On HostA, I have a process, procA, that does I/O, like so:
#!/bin/bash
while sleep 1 ; do
# Consume input *if available*
if read -t 0.5 x; then # a timed-read
# If input is available, output it.
echo "HostA Input: $x"
fi
# Produce some output.
echo "HostA Output: $(date)"
done
On HostB, I have a very similar process, procB, with the only difference that procB tags its input/output with the prefix HostB (instead of the prefix HostA).
Now, I want to use the netcat program (/usr/bin/nc) to send procA‘s stdout to procB‘s stdin, and procB‘s stdout to procA‘s stdin. My expectation in all this is that HostA’s output should appear on HostB, and HostB’s output should appear on HostA… much as would happen in following canonical nc example of a peer-to-peer chat:
[HostB]$ nc -l 4000
[HostA]$ nc HostB 4000
But, when I tried to extend the above canonical example by replacing the human at both hosts with processes procA and procB as follows, it did not work:
On HostB:
$ mkfifo p
$ ./procB <p | nc -l 4000 >p
<WHY NO OUTPUT HERE??>
and, on HostA:
$ mkfifo p
$ ./procA <p | nc HostB 4000 >p
<WHY NO OUTPUT HERE??>
Notes:
- I have verified that port 4000 is open on HostB.
- Unidirectional communication, such as the following, seems to work:
On HostB:
$ mkfifo p
$ ./procB <p | nc -l 4000 >p
On HostA:
$ ./procA | nc HostB 4000
HostB Output: Wed Jan 11 13:53:37 IST 2012
HostB Output: Wed Jan 11 13:53:39 IST 2012
HostB Input: HostA Output: Wed Jan 11 13:55:02 IST 2012
HostB Output: Wed Jan 11 13:53:40 IST 2012
HostB Input: HostA Output: Wed Jan 11 13:55:04 IST 2012
HostB Output: Wed Jan 11 13:53:41 IST 2012
HostB Input: HostA Output: Wed Jan 11 13:55:05 IST 2012
HostB Output: Wed Jan 11 13:53:42 IST 2012
^C
Now, I know that nc comes with an INSECURE option -e that could somehow be employed if it’s enabled in your nc binary, but assuming that I don’t have -e option available, how can I connect 2 remote processes to each other via nc? Basically, where I’m going wrong above? Why there is no output in the places I have indicated above? Many thanks in advance.
The behavior described above is actually the right behavior, just that I did not realize that it was.
Wherever I was complaining about
<WHY NO OUTPUT HERE??>, it was/is because the stdout’s of the terminals have been redirected to the local fifos. (No wonder, you don’t see anything on the terminal!)Further, in Notes (2) above, it is not really true that the communication is unidirectional; it is very much bidirectional, just that you don’t get to see any output on HostB, once again, because stdin and stdout have redirected from the terminal to the fifo. Thus, you correctly see
procB‘s output on HostA, which is nothing but the output ofprocAon HostA sent toprocBon HostB asprocB‘s input!Wow!
EDIT:
To actually see the output on each terminal, use
tee, like so:On HostB:
On HostA: