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!!!

3
  • 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, 2013 at 19:53
  • Or if you run nc from a screen session?
    – tink
    Mar 21, 2013 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, 2013 at 20:39

2 Answers 2

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 &
1
  • Brilliant! Thank you for the explanation, that makes a lot of sense. It worked perfectly. Mar 22, 2013 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 &
1
  • This should be the accepted solution Jan 9, 2016 at 13:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .