0
cat hello.txt | nc -l 14223 > hello.txt

hello.txt originally has "Hello!" in it. I know if I use mypipe instead of hello.txt, then it works. But I don't quite understand: (1) why netcat closes its connection automatically (2) why nothing shows up on both windows (3) why hello.txt is erased.

Anonny
  • 459
  • 1
  • 3
  • 17
  • What are you expecting that code to do, exactly? – Blorgbeard Nov 14 '17 at 20:03
  • 1
    Pipelines run all at once, so the `> hello.txt` takes place -- emptying out the file -- at the same time `cat hello.txt` does. And because starting an external program like `cat` takes some time, in almost all cases the file will be emptied as part of the process of setting it up as to receive output before any part of it is read as input. – Charles Duffy Nov 14 '17 at 20:06
  • (You shouldn't use `cat` here at all in the first place -- it's more efficient to run `nc -l 14223 hello.out`: No pipeline, just stdin and stdout redirected to two different files). – Charles Duffy Nov 14 '17 at 20:08
  • 1
    1. Netcat will close its connection after the first accept() unless you provide the `-k`/`--keep-open` parameter. `ncat -lk 14223` 2. The reason this happens is due to the answer of #3 3. Bash (and other shells) will process the redirections **first**. By the time `cat hello.txt` is executed, it's already been overwritten by the redirection opening the file in write mode. Here's a simple example to demonstrate this: https://i.gyazo.com/9ff618bb670e08296e86e91a1bc31bfa.png – Goodies Nov 14 '17 at 20:09
  • Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Super User](http://superuser.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask. – jww Nov 14 '17 at 20:59

0 Answers0