Reputation: 132
If I open an nc in listening on Terminal1
nc -l 35555
And perform a connection in this way on Terminal2
mkfifo /tmp/f
cat /tmp/f | nc 127.0.0.1 35555 > /tmp/f
Now I have few questions
On Terminal2 you can see something in waiting. What is that?
If I write a string on Terminal1, that string just come back.
cat /tmp/f | nc 127.0.0.1 35555 > /tmp/f
doesn't create a cycle?The received string comes out from nc and goes in /tmp/f. Because of the cat that string begins input of nc, sent back to Terminal1 and again in /tmp/f etc. etc.
Thanks.
Upvotes: 1
Views: 972
Reputation: 780688
- Is it the cat process or the nc process?
It's both. cat
is waiting for something to be written to the FIFO. nc
is waiting for something to be written to its stdin
or to receive something over the network socket.
- In which order are they executed?
All commands in a pipeline are run concurrently.
- Why
cat /tmp/f | nc 127.0.0.1 35555 > /tmp/f
doesn't create a cycle?
The first terminal is not sending back what it received from the network, it just prints it to the terminal. When you type something on terminal 1 it gets written to the network once. nc
on terminal 2 writes it to /tmp/f
. Then it reads it and sends it to the network. nc
on terminal 1 reads it and prints it. That's the end.
-Why isn't the cat of a fifo a blocking operations? Technically it not end, so why the nc is executed?
Commands in a pipeline don't wait for the previous one to exit. That would make it impossible to write code like
tail -f filename | grep word
since tail -f
never exits (until you kill it with Ctl-c, but that also kills grep
). All the processes run, which allows the later programs to process partial output of the earlier programs.
So nc
doesn't wait for cat
to exit. It runs at the same time, and probably uses select()
or epoll()
to listen for input from both stdin
and the network socket at the same time (it might also use separate threads for each). So while cat
is blocking on the FIFO, it can read the network data from terminal 1, and then write it to the FIFO.
Upvotes: 3