2

I want to use netcat to dump a number of blocks of strings to a file. I've been running this in my linux terminal and everything works very well until I try to detach my command line. If I run my command as a detached session netcat stops after the first round of strings.

In short, this works:

nc localhost 3000 > test.txt

But this doesn't:

nc localhost 3000 > test.txt &
[1] 9040
max@starbuck ncats]$ 

[1]+  Stopped                 nc localhost 3000 > test.txt

I suppose this has to do with reaching the end of a send on the server side, but I don't know enough about netcat to tell it, "hey! stay awake until your connection drops"

Ideas? Thanks!!!

  • My guess is that nc is trying to read from its controlling terminal and is getting SIGTTIN and stopping. Does it work if you add </dev/null to the nc command line to tell it to not try to read from standard input? – rra Mar 21 '13 at 19:53
  • Or if you run nc from a screen session? – tink Mar 21 '13 at 19:54
  • adding < /dev/null just causes it to exit immediately. Screen is a possibility, but doesn't explain why this happens. I'll use screen if I can't figure it out. – Maxwell Bottiger Mar 21 '13 at 20:39
1

netcat wants to send its stdin across the socket and print out the response, so it expects to have them both connected and active. I don't know a good way of creating a command that waits forever, but you could try

sleep 86400000 | nc localhost 3000 > test.txt &
| improve this answer | |
  • Brilliant! Thank you for the explanation, that makes a lot of sense. It worked perfectly. – Maxwell Bottiger Mar 22 '13 at 12:50
1

Some versions of nc support the -d option (noteably the OpenBSD version), which prevents it from trying to read from stdin.

So the code would become:

nc localhost 3000 -d > test.txt &
| improve this answer | |
  • This should be the accepted solution – Daniel Alder Jan 9 '16 at 13:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.